JSR 223 specifies the interaction between the script language running on the Java virtual machine and the Java program. JSR 233 is part of Java se 6, and the package in the API in the Java table is javax.script.
According to the practice, what do I do to call dynamic language script
If there is such a situation: it is necessary to judge the size of a variable a, but the judgment rule is uncertain, which may be a < 1, a > 1, a == 1, etc.
- The following is the implementation without calling dynamic script:
public boolean compare(double a, String expression) { int n = Integer.parseInt(expression.replaceAll("\\D", "")); if(expression.contains(">=")) { return a >= n; } else if(expression.contains("<=")) { return a < n; } else if(expression.contains("==")) { return a == n; } else if(expression.contains(">")) { return a > n; } else { ... } }
It's a lot of trouble to realize. It's just a bunch of judgments. But for a < 1 & & a > 0, this kind of complex expression is more difficult to implement.
- The following is the implementation of calling js script:
public boolean compare(double a, String expression) throws Exception{ expression = expression.replace("a", a) ScriptEngineManager sem = new ScriptEngineManager(); ScriptEngine scriptEngine = sem.getEngineByName("js"); return scriptEngine.eval(expression); }
In this way, it is very simple and can deal with complex expressions.
The following is a comparison between executing js script and lua script:
- Execute js script
Test code
int size = 10000; ScriptEngineManager sem = new ScriptEngineManager(); ScriptEngine scriptEngine = sem.getEngineByName("js"); long start = System.currentTimeMillis(); for (int i = 0; i < size; i++) { String jsStr = String.format("%d > %d", i, i+1); try{ scriptEngine.eval(jsStr); }catch (Exception e) { e.printStackTrace(); } } long end = System.currentTimeMillis(); System.out.printf("js: %d ms\n" ,end - start);
- Execute lua script
Need the support of the third-party library Luaj
Luaj is a lua interpreter based on lua version 5.2. X, which considers the following objectives:
- The Java centric lua vm implementation aims to take advantage of standard Java functions.
- Lightweight, high-performance lua execution.
- Multiple platforms that can run in JME, JSE, or JEE environments.
- A complete library and toolset for integration into the actual project.
- Due to the sufficient unit test of vm and library functions, it is reliable.
Test code
int size = 100000; Globals globals = JsePlatform.standardGlobals(); long start = System.currentTimeMillis(); for (int i = 0; i < size; i++) { String luaStr = String.format("return %d > %d", i, i+1); LuaValue chunk = globals.load(luaStr); chunk.call().toboolean(); } long end = System.currentTimeMillis(); System.out.printf("lua: %d ms\n", end - start);
Average execution time
lua: 900 ms
javascript: 60000 ms
The execution efficiency of lua script is much higher than that of js script.