Skip to content

Instantly share code, notes, and snippets.

@rusintez
Forked from billywhizz/script_test.js
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rusintez/ae550bdff9449f23daf1 to your computer and use it in GitHub Desktop.
Save rusintez/ae550bdff9449f23daf1 to your computer and use it in GitHub Desktop.
var vm = require('vm'),
code = 'var square = n * n;',
fn = new Function('n', code),
script = vm.createScript(code),
sandbox;
n = 5;
sandbox = { n: n };
benchmark = function(title, funk) {
var end, i, start;
start = new Date;
for (i = 0; i < 5000; i++) {
funk();
}
end = new Date;
console.log(title + ': ' + (end - start) + 'ms');
}
var ctx = vm.createContext(sandbox);
benchmark('vm.runInThisContext', function() { vm.runInThisContext(code); });
benchmark('vm.runInNewContext', function() { vm.runInNewContext(code, sandbox); });
benchmark('script.runInThisContext', function() { script.runInThisContext(); });
benchmark('script.runInNewContext', function() { script.runInNewContext(sandbox); });
benchmark('script.runInContext', function() { script.runInContext(ctx); });
benchmark('fn', function() { fn(n); });
/*
vm.runInThisContext: 10ms
vm.runInNewContext: 1432ms
script.runInThisContext: 4ms
script.runInNewContext: 1426ms
script.runInContext: 49ms
fn: 0ms
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment