With Java ScriptEngine (Groovy), how to make it more performant?

后端 未结 1 1498
耶瑟儿~
耶瑟儿~ 2020-12-28 21:14

I am using ScriptEngine in my app to evaluate some client code in my application. The problem is it\'s not performant enough and I need to take measures to improve the time

相关标签:
1条回答
  • 2020-12-28 21:30

    Most likely the problem is that the engine actually evaluates the script every time eval() is called. Instead, you could re-use the precompiled script via Compilable interface.

        // move this into initialization part so that you do not call this every time.
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine  = manager.getEngineByName("groovy");
        CompiledScript script = ((Compilable) engine).compile(urlGeneratorScript);
    
        //the code below will use the precompiled script code
        Bindings bindings = new Bindings();
        bindings.put("state", state;
        bindings.put("zipcode", zip);
        bindings.put("url", locationAwareAd.getLocationData().getGeneratedUrl());
        url = script.eval(bindings);
    

    FWIW, you can also implement the file timestamp check, if the script is changed call compile(..) again.

    0 讨论(0)
提交回复
热议问题