使用Java ScriptEngine(Groovy),如何使它更具性能? [英] With Java ScriptEngine (Groovy), how to make it more performant?

查看:5582
本文介绍了使用Java ScriptEngine(Groovy),如何使它更具性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序中使用ScriptEngine来评估应用程序中的某些客户端代码。
问题在于性能不够好,我需要采取措施来缩短执行时间。
目前,它可能需要长达1463毫秒(平均300毫秒左右)来评估一个非常简单的脚本,它基本上是在URL中进行参数替换的。

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 of execution. Currently, it can take up to 1463ms (average is around 300ms) to eval an extremely simple script which is basically parameter replacement in URLs.

我是寻找简单的策略来改善这种性能而不会失去脚本功能。

I'm looking for simple strategies to improve this performance without losing the scripting ability.

我首先想到了将ScriptEngine对象集中并重用它。我在规范中看到它的目的是被重用,但我还没有找到任何实际做它的例子。

My first thought it to pool the ScriptEngine object and reuse it. I see in the spec it's meant to be reused but I haven't found any examples of anyone actually doing it.

任何想法?
这里是我的代码:

Any ideas? Here is my code:

ScriptEngineManager factory = new ScriptEngineManager();
GroovyScriptEngineImpl engine = (GroovyScriptEngineImpl)factory.getEngineByName("groovy");
engine.put("state", state;
engine.put("zipcode", zip);
engine.put("url", locationAwareAd.getLocationData().getGeneratedUrl());
url = (String) engine.eval(urlGeneratorScript);

请注意!

推荐答案

最可能的问题是每次调用eval()时引擎实际评估脚本,您可以通过 Compilable 界面重新使用预编译脚本。

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,你也可以实现文件时间戳检查,如果脚本被改变,再次调用compile(..)。

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

这篇关于使用Java ScriptEngine(Groovy),如何使它更具性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆