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

查看:175
本文介绍了使用 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天全站免登陆