我有一个
Java程序(使用JDK 7u80编译),它广泛使用了“
Javascript”ScriptEngine(JSR-223).与Java 7运行时环境(JRE 7u80)相比,我在Java 8运行时环境(JRE 8u65)下执行时,我的程序运行速度非常慢.
我已经将以下SSCCE放在一起来演示这个问题,然后在同一个Windows PC上的Java 7和Java 8下执行它:
import javax.script.*;
public class SSCCE {
public SSCCE() {
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine js = sem.getEngineByName("Javascript");
long t = 0;
int i = 0;
String gJs = "function ip2long(ip) {";
gJs += "var aIP = ip.split(\".\");";
gJs += "return (aIP[0] * Math.pow(256, 3)) + (aIP[1] * Math.pow(256, 2)) + (aIP[2] * 256) + (aIP[3] * 1);";
gJs += "}";
gJs += "function long2ip(l) {";
gJs &#43;&#61; "if (!isNaN(l) && ((l >&#61; 0) || (l <&#61; Math.pow(2, 32)))) {";
gJs &#43;&#61; "return Math.floor(l / Math.pow(256, 3)) &#43; \".\" &#43;";
gJs &#43;&#61; "Math.floor((l % Math.pow(256, 3)) / Math.pow(256, 2)) &#43; \".\" &#43;";
gJs &#43;&#61; "Math.floor(((l % Math.pow(256, 3)) % Math.pow(256, 2)) / Math.pow(256, 1)) &#43; \".\" &#43;";
gJs &#43;&#61; "Math.floor((((l % Math.pow(256, 3)) % Math.pow(256, 2)) % Math.pow(256, 1)) / Math.pow(256, 0));";
gJs &#43;&#61; "}";
gJs &#43;&#61; "return null;";
gJs &#43;&#61; "}";
try {
js.eval(gJs);
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println("Warming Up...");
t &#61; System.nanoTime();
for (i &#61; 0; i <4097; i&#43;&#43;) {
try {
String sJs &#61; "var ip &#61; \"192.0.2.0\";";
sJs &#43;&#61; "var nip &#61; long2ip(ip2long(ip, " &#43; i &#43; "));";
js.eval(sJs);
}
catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("Starting...");
t &#61; System.nanoTime();
for (i &#61; 0; i <4097; i&#43;&#43;) {
try {
String sJs &#61; "var ip &#61; \"192.0.2.0\";";
sJs &#43;&#61; "var nip &#61; long2ip(ip2long(ip, " &#43; i &#43; "));";
js.eval(sJs);
}
catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("Elapsed Time: " &#43; (System.nanoTime() - t) / 1000000000.0f);
}
public static void main(String[] args) {
new SSCCE();
}
}
Javascript由一个将IP地址转换为一个长度的函数组成,添加一个数字,然后将其转换回一个IP地址 – 这是重复4096次.
我在Java 7和Java 8之间看到以下结果&#xff1a;
D:\Scripts>java7 SSCCE
Warming Up...
Starting...
Elapsed Time: 0.5856594
D:\Scripts>java8 SSCCE
Warming Up...
Starting...
Elapsed Time: 4.6862915
我应该把它提升为与Java 8相关的性能错误吗&#xff1f;
更新&#xff1a;包括预热阶段,以确保在我的定时循环之前已经初始化了所有代码路径.