Skip to content

Instantly share code, notes, and snippets.

@sonygod
Created April 15, 2013 10:22
Show Gist options
  • Select an option

  • Save sonygod/5387168 to your computer and use it in GitHub Desktop.

Select an option

Save sonygod/5387168 to your computer and use it in GitHub Desktop.
nodejs vm
var vm = require('vm'),
code = 'var square = n * n; console.log(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 < 5; i++) {
funk();
}
end = new Date;
console.log(title + ': ' + (end - start) + 'ms n='+n);
}
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
*/
function say(value){
console.log("hello"+value);
}
var offer = {title:'fdsfds',price:323,value:140};
var initSandbox = {
http: 123,
offer: offer,
done : function(offer) {
console.log('done!'+offer.value);
},
setTimeout: setTimeout,
say:say
};
var context = vm.createContext(initSandbox);
vm.runInContext("setTimeout(done,100,offer);say('sonygod')", context);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment