Resolve 'vm.runInContext' bottleneck

Calling 'vm.runInContext'  is slightly more expensive then calling `eval`, but removing the string template and extracting the variable generator helps abit.
master
Futago-za Ryuu 6 years ago
parent 43a305eaef
commit fedf0f3480

@ -1,25 +1,50 @@
"use strict";
const vm = {
const VM_VARS = {
runInContext( code, context ) {
"module": true,
"process": true,
"VM_VARS": true,
"PREFACE_VARS": true,
"generateDeclaration": true,
"runInContext": true,
"code": true,
"preface": true,
const peg$context = typeof context !== "undefined" ? context : {};
};
const PREFACE_VARS = Object.keys( VM_VARS )
.map( name => `var ${ name } = void 0;` )
.join( " " );
function generateDeclaration( name ) {
return ( ! VM_VARS[ name ] ? "var " : "" )
+ `${ name } = vm$context.${ name };`;
}
module.exports = {
/* eslint indent: 0 */
return eval( `
${
Object.keys( peg$context )
.map( key => `var ${ key } = peg$context.${ key };` )
.join( "" )
}
var vm = null, code = null, context = null;
// `eval` the given code, using properties found in `context` as top-level
// variables, while hiding some variables in this module from the code.
//
// Based on `vm.runInContext` found in Node.js, this is a cross-env solution.
runInContext( code, vm$context ) {
let preface = PREFACE_VARS;
if ( typeof vm$context === "object" ) {
preface += Object.keys( vm$context )
.map( generateDeclaration )
.join( " " );
}
return eval( preface + code );
${ code }
` );
},
};
module.exports = vm;

Loading…
Cancel
Save