15.7.10

Make My Java Program Supports Dynamic Language (1)

In the coming JDK 7, Dynamic Language support is one of the significant features. The feature in JDK 7 implements JSR 292: Supporting Dynamically Typed Languages on the Java Platform, which is logical follow-to JSR 223: Scripting for the Java Platform. Support for JSR 223 was provided as part of Java SE 6 and implemented in JDK 6.

Just look at this piece of sample code:

Code Example 1: Create a ScriptEngine object using the engine name.

  ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
try {
jsEngine.eval("print('Hello, world!')");
} catch (ScriptException ex) {
ex.printStackTrace();
}

You see, ScriptEngine.eval() is the only way to execute the script. That means, the script is the script every time and you might have no way to optimize it. Here is a performance comparison between  Groovy, Java Script Engine and Java native implementation using Reflection to do a simple loop:






































 Java ReflectionGroovyScript Engine
1000,000(times)4(ms)690(ms)524(ms)
1000,000
(2nd testing)
2(ms)18-
10,000,0005730(ms)12,743(ms)
10,000,0005642(ms)-
100,000,000476,053(ms)103,392
100,000,000(2nd testing)466,035(ms)-

That means, Script Engine using JavaScript is about 17 times slower than Groovy Scripts 2,199 times slower than the native Java call (by reflection).


(To be continue…)

No comments: