Skip to content

Instantly share code, notes, and snippets.

@stuartc
Created September 5, 2016 10:08
Show Gist options
  • Save stuartc/c887f2c5287e6d757f07c3589cabbef1 to your computer and use it in GitHub Desktop.
Save stuartc/c887f2c5287e6d757f07c3589cabbef1 to your computer and use it in GitHub Desktop.
'use strict';
// https://60devs.com/executing-js-code-with-nodes-vm-module.html
var code = `
// global script scope
function nop() {
};
var i = 1000000; // global script scope
while (i--) {
nop(); // access global scope
}
console.log('done');
`;
console.time('eval');
eval(code);
console.timeEnd('eval');
var vm = require('vm');
var context = vm.createContext({ console });
var script = new vm.Script(code);
console.time('vm');
script.runInContext(context);
console.timeEnd('vm');
var context = vm.createContext({ console });
var script = new vm.Script(`(function() { ${code} })()`);
console.time('iife vm');
script.runInContext(context);
console.timeEnd('iife vm');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment