Created
September 5, 2016 10:08
-
-
Save stuartc/c887f2c5287e6d757f07c3589cabbef1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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