我正在尝试以下代码进行性能检查。它纯粹是 CPU 密集型的,对类型进行大量计算double
,单线程,并且不使用任何堆:
public class PerfTestSampleJ {
private static final int MEASURE_COUNT = 5;
private static final int ITERATIONS = 100_000_000;
public static void main(String[] args) {
var minTime = Long.MAX_VALUE;
for (int i = 1; i <= MEASURE_COUNT; i++) {
long start = System.nanoTime();
double pi = calculatePi(ITERATIONS);
long time = System.nanoTime() - start;
System.out.printf("Iteration %2d took %8.3f ms%n", i, time / 1e6);
if (time < minTime) {
minTime = time;
}
if (Math.abs(pi - Math.PI) > 1e-14)
throw new AssertionError(pi + " (" + (pi - Math.PI) + ")");
}
System.out.printf("Minimum time taken: %8.3f ms%n", minTime / 1e6);
}
private static double calculatePi(int iterations) {
double pi = 0.0;
double numerator = 4.0;
for (int i = 1; i <= iterations; i++) {
double n = i * 2.0;
double denominator = n * (n + 1) * (n + 2);
pi += numerator / denominator;
numerator = -numerator;
}
return 3 + pi;
}
}
现在,使用相同的编译类文件,比较在 JRE 21 和 JRE 23 下运行的结果:
/usr/lib/jvm/jdk-21.0.5-oracle-x64/bin/java PerfTestSampleJ
Iteration 1 took 801.058 ms
Iteration 2 took 798.392 ms
Iteration 3 took 414.688 ms
Iteration 4 took 413.959 ms
Iteration 5 took 416.867 ms
Minimum time taken: 413.959 ms
/usr/lib/jvm/jdk-23.0.1-oracle-x64/bin/java PerfTestSampleJ
Iteration 1 took 193.654 ms
Iteration 2 took 186.790 ms
Iteration 3 took 102.963 ms
Iteration 4 took 103.226 ms
Iteration 5 took 102.869 ms
Minimum time taken: 102.869 ms
在每次运行中,前两次迭代都有一个预热阶段,但第三次迭代及以后的速度几乎是最快的。
Java 23 中有哪些变化可以加快速度?查看发行说明时,我发现有关性能的所有信息都是垃圾收集器的改进。但我们这里不使用堆,因此垃圾收集器的改进无关紧要。
PS 以上结果是在使用 i7 处理器的 Ubuntu Linux x64 上得出的。我使用 Temurin 版本也得到了相同的结果。此外,我在 Windows x64 上尝试了 Oracle JRE 22 与 23,结果相似,显示性能差异在 22 和 23 之间。