node.jsは最近、仮想マシンモジュールを追加しました。実際、それが新しいものであるとは言えません。 2.xから利用できる内部インターフェイスを露出するだけです。これらのコードは、node/src/node.jsから見ることができます:
var script = process.binding( 'evals')。nodescript; var runinthiscontext = script.runinthiscontext; nativemodule.wrap = function(script){return nativemodule.wrapper [0] + script + nativemodule.wrapper [1]; }; nativemodule.wrapper = ['(function(exports、require、module、__ filename、__dirname){'、 '/n});' ]; nativemodule.prototype.compile = function(){var source = nativemodule.getSource(this.id); source = nativemodule.wrap(source); var fn = runinthiscontext(source、this.filename、true); fn(this.exports、nativemodule.require、this、this.filename); this.loaded = true; };その中のスクリプトオブジェクトは、要求( 'VM')によって返されるオブジェクトと非常に似ていますが、本質的に、VMモジュールはスクリプトオブジェクトのカプセル化です。
var script = process.binding( 'evals')。nodescript; console.log(script)/** {[function:nodeScript] createcontext:[function]、runincontext:[function]、runinthiscontext:[function]、runinewcontext:[function]}*/console.log( 'vm'){vm '){creat(' vm '){bm') [function]、runincontext:[function]、runinthiscontext:[function]、runinnewcontext:[function]}、createscript:[function]、createcontext:[function]、runincontext:[function]、runinthiscontext:[function]、runinnewcontext:[function]}その中でも、Runinthiscontextは新しい環境でコードを実行することと同等であり、現在の範囲のオブジェクトには影響しません。 runinnewContextとrunIncontextはコンテキストオブジェクトとして指定できます。違いは通常のオブジェクトまたはコンテキストオブジェクトです。言い換えれば、runinnewContextとrunIncontextは、現在の範囲のオブジェクトに局所的に影響を与える可能性があります。現在の環境と完全に相互作用するには、危険な回避が必要です。 node.jsに付属のローディングシステムでは、明らかにそれほど勇気がなく、runinthiscontextを使用します。そして、私はこれの前に多くの作業を行いました。たとえば、ユーザーのJSファイルのコンテンツをレイヤー(NativeModule.Wrap)にラッピングし、その他の散布操作に加えて、実際には非常に効率的なロード方法です。唯一の利点は、同期が使用され、コードの書き込みがはるかに簡単になることです。
GitHubでは、スクリプトを動的に実行するこれらの方法のパフォーマンスを比較しています。
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.runnenenenenwcontext'( 'vm.runnewcontext'、code()) sandbox); benchmark( 'script.runinthiscontext'、function(){script.runinthiscontext();}); benchmark( 'script.runnewcontext'、function(){script.runinewcontext '、function() function(){script.runinewcontext(sandbox); benchmark( 'script.runincontext'、function(){script.runincontext(ctx);}); benchmark( 'fn'、function(){fn(n);}); 2222msscript.runinthiscontext:6msscript.runinnewcontext:1876msscript.runincontext:44msfn:0ms */このことから、V8メソッドが完全な勝利であることがわかります!
上記は、この記事のコンテンツ全体です。参照を提供できることを願っています。wulin.comをもっとサポートできることを願っています。