Skip to content

Instantly share code, notes, and snippets.

@bryanhelmig
Forked from billywhizz/script_test.js
Last active November 24, 2016 05:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bryanhelmig/c7bed4576c7e270796a4 to your computer and use it in GitHub Desktop.
Save bryanhelmig/c7bed4576c7e270796a4 to your computer and use it in GitHub Desktop.
record time spent on "each" run for nodejs or node vm module vs contextify, etc.
var vm = require('vm'),
Contextify = require('contextify'),
code = 'var square = n * n;',
fn = new Function('n', code),
script = vm.createScript(code);
n = 5;
benchmark = function(title, funk) {
var end, i, start, spins = 10000;
start = new Date;
for (i = 0; i < spins; i++) {
funk();
}
end = new Date;
console.log(title + ': ' + (end - start) / spins + 'ms per run');
}
var ctx = vm.createContext({n: n});
var reusedSandbox = {n: n};
Contextify(reusedSandbox);
benchmark('vm.runInThisContext', function() { vm.runInThisContext(code); });
benchmark('vm.runInNewContext', function() { vm.runInNewContext(code, {n: n}); });
benchmark('script.runInThisContext', function() { script.runInThisContext(); });
benchmark('script.runInNewContext', function() { script.runInNewContext({n: n}); });
benchmark('script.runInContext', function() { script.runInContext(ctx); });
benchmark('reused contextify', function() { reusedSandbox.run(code); });
benchmark('new contextify', function() { var sandbox = {n: n}; Contextify(sandbox); sandbox.run(code); sandbox.dispose(); });
benchmark('eval', function() { eval(code); });
benchmark('fn', function() { fn(n); });
/*
vm.runInThisContext: 0.0011ms per run
vm.runInNewContext: 0.2967ms per run
script.runInThisContext: 0.0008ms per run
script.runInNewContext: 0.2881ms per run
script.runInContext: 0.1716ms per run
reused contextify: 0.0018ms per run
new contextify: 0.3195ms per run
eval: 0.001ms per run
fn: 0ms per run
*/
@bryanhelmig
Copy link
Author

For iojs - its a bit slower:

root@08278136ab03:/# iojs test.js
vm.runInThisContext: 0.002ms per run
vm.runInNewContext: 24.853ms per run
script.runInThisContext: 0.001ms per run
script.runInNewContext: 30.514ms per run
script.runInContext: 0.009ms per run
reused contextify: 0.002ms per run
new contextify: 33.316ms per run
eval: 0.001ms per run
fn: 0.001ms per run

Nodejs proper is a bit faster:

root@9a780e47dc4b:/# node test.js
vm.runInThisContext: 0.005ms per run
vm.runInNewContext: 11.437ms per run
script.runInThisContext: 0.002ms per run
script.runInNewContext: 12.136ms per run
script.runInContext: 0.338ms per run
reused contextify: 0.001ms per run
new contextify: 12.797ms per run
eval: 0.016ms per run
fn: 0.001ms per run

Both in boot2docker containers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment