求助:node.js vm 模块在什么情况下使用?
发布于 5个月前 作者 hackerjs 384 次浏览
//作了个vm 测试
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('vm.runInContext', function() { vm.runInContext(code, ctx); });
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: 5ms vm.runInNewContext: 2799ms vm.runInContext: 1325ms script.runInThisContext: 5ms script.runInNewContext: 2585ms script.runInContext: 1373ms fn: 0ms

vm 模块在什么情况下使用呢

回到顶部