nashorn CompiledScript graalvm 等价物

nashorn CompiledScript graalvm equivalent

我有一个相当大的文件需要经常评估,

我曾经用 nashorn 做过类似的事情:

CompiledScript compiledScript = ((Compilable) engine).compile(text);

后来,我可以多次调用以下内容:

Context context = new SimpleScriptContext();
compiledScript.eval(context);

这相当快。

使用新的 Polyglot API,我这样做 :

Source source = Source.newBuilder("js", myFile).build();

然后 :

Context context = Context.newBuilder("js").option("js.nashorn-compat", "true").build();
context.eval(source)

使用jmh,我觉得两者性能差别很大

Benchmark                     Mode  Cnt   Score    Error  Units
JmhBenchmark.testEvalGraal    avgt    5  42,855 ± 11,118  ms/op
JmhBenchmark.testEvalNashorn  avgt    5   2,739 ±  1,101  ms/op

如果我在同一上下文中执行 eval,它会正常工作,但我不想在两个连续的 eval 之间共享上下文(除非上下文的概念Graal 与 Nashorn 的不同)。

要使用 GraalVM 重现您的 ScriptEngine 设置,您应该在使用后重新使用相同的 Engine (org.graalvm.polyglot.Engine) 和 .close() 上下文:

Source source = Source.newBuilder("js", myFile).build();
Engine engine = Engine.create();

及以后:

Context context = Context.newBuilder("js")
                         .engine(engine)
                         .option("js.nashorn-compat", "true").build();
context.eval(source);
context.close();

引用 Context.Builder.engine documentation:

Explicitly sets the underlying engine to use. By default, every context has its own isolated engine. If multiple contexts are created from one engine, then they may share/cache certain system resources like ASTs or optimized code by specifying a single underlying engine.