有人知道为什么我在Java 8和Java 11上运行这段代码时会得到如此不同的性能吗?
在不使用任何运行时标志的情况下,与Java 8相比,此代码在Java 11下的运行速度似乎要慢得多。
import java.util.Date;
public class PerformanceExperiment {
public static volatile String s = "";
public static void main(String[] args)
{
System.out.println("Starting performance test");
String s1 = "STRING ONE";
String s2 = "STRING TWO";
long now1 = (new Date()).getTime();
for (long i = 0; i < 1_000_000_00; i++)
{
s = "abc " + s1 + " def " + s2;
}
long now2 = (new Date()).getTime();
System.out.println("initial block took " + (now2 - now1) + "ms");
for (long i = 0; i < 4_000_000_00; i++)
{
s = "abc " + s1 + " def " + s2;
}
long now3 = (new Date()).getTime();
System.out.println("Main block took " + (now3 - now2) + "ms");
}
}我尝试了许多命令行标记,但都没有找到与Java 8性能匹配的任何标记。
我只在Windows上进行了测试,所以它在其他操作系统上的表现可能会有所不同。
发布于 2019-03-28 21:03:15
我修改了你的应用程序
Netbeans profiler使用System.nanoTime()代替new Date()以获得更高的精度(有关更多信息,请参见此答案:https://stackoverflow.com/a/1776053/963076).
将Netbeans 8.2与JDK 8 v181配合使用:
Starting performance test 0
initial block took 3147ms
Main block took 9469ms
Starting performance test 1
initial block took 2398ms
Main block took 9601ms
Starting performance test 2
initial block took 2463ms
Main block took 9671ms
Starting performance test 3
initial block took 2464ms
Main block took 9565ms
Starting performance test 4
initial block took 2410ms
Main block took 9672ms
Starting performance test 5
initial block took 2418ms
Main block took 9598ms
Starting performance test 6
initial block took 2384ms
Main block took 9733ms
Starting performance test 7
initial block took 2402ms
Main block took 9610ms
Starting performance test 8
initial block took 2509ms
Main block took 11222ms
Starting performance test 9
initial block took 2455ms
Main block took 10661ms剖面仪显示了这个遥测结果:

对于使用JDK 11.0.2的Netbeans 10.0:
Starting performance test 0
initial block took 3760ms
Main block took 15056ms
Starting performance test 1
initial block took 3734ms
Main block took 14602ms
Starting performance test 2
initial block took 3615ms
Main block took 14762ms
Starting performance test 3
initial block took 3748ms
Main block took 14534ms
Starting performance test 4
initial block took 3628ms
Main block took 14759ms
Starting performance test 5
initial block took 3625ms
Main block took 14959ms
Starting performance test 6
initial block took 3987ms
Main block took 14967ms
Starting performance test 7
initial block took 3803ms
Main block took 14701ms
Starting performance test 8
initial block took 3599ms
Main block took 14762ms
Starting performance test 9
initial block took 3627ms
Main block took 14434ms

我的结论是: JDK 11正在做更多的工作来提高内存效率。请注意,使用JDK11时,垃圾收集器中的“幸存世代”数量要少得多,内存使用量和易失性也要少得多。权衡似乎是在速度上,但速度的差异小于内存使用的差异。
https://stackoverflow.com/questions/55395958
复制相似问题