java scriptengine,使用Java ScriptEngine(Groovy),如何使它更具性能?

博客讨论了在应用程序中使用ScriptEngine执行客户端代码时遇到的性能问题。作者指出,每次调用eval()方法都会重新评估脚本,导致延迟。为了解决这个问题,提出了通过Compilable接口预编译脚本来提高执行速度的方案。通过预编译和使用Bindings对象,可以显著减少执行时间。博客提供了具体的代码示例来展示如何实现这一优化策略。
摘要由CSDN通过智能技术生成

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.

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);

Any feedback would be appreciated!

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值