Search code examples
graalvmgraaljs

Is it possible to store and load precompiled js to org.graalvm.polyglot.Context


It there any way to convert javascript source into some pre-compiled stated that can be stored and loaded somehow to org.graalvm.polyglot.Context instead of eval-ing it as a raw String? Something like undocumented --persistent-code-cache in nashorn.


Solution

  • As of May'19, you can share code within the same process to avoid reparsing (similar to the Nashorn code persistence) by reusing the same Engine object between different Contexts like this:

    try (Engine engine = Engine.create()) {
        Source source = Source.create("js", "21 + 21");
        try (Context context = Context.newBuilder().engine(engine).build()) {
            int v = context.eval(source).asInt();
            assert v == 42;
        }
        try (Context context = Context.newBuilder().engine(engine).build()) {
            int v = context.eval(source).asInt();
            assert v == 42;
        }
    }
    

    More details can be found here: https://www.graalvm.org/docs/graalvm-as-a-platform/embed/#enable-source-caching

    We have plans to support persistent code cache across processes in combination with the GraalVM native-image tool in the future. We already support creating native-images that contain the JavaScript interpreter and the GraalVM compiler. We want to add support for allowing to include pre-warmed up scripts, hopefully with pre-compiled JavaScript native-code as well. So you might be able to start your JS application with close to zero startup time. No ETA though.