我试图了解当代码被执行多次时,我可以在 Java 中实现什么样的编译时优化。我对以下场景中的算术简化特别感兴趣:
想象一下,您需要使用相同的 3d 仿射变换来变换一百万个 3d 点。如果转换结果是纯翻译,那么一个好的优化器将能够将 12 次乘法和 12 次加法仅转换为 3 次加法,因为所有乘法都是乘以 1,而许多加法都是带零的加法。
在尝试这个“复杂场景”之前,我只是在循环中运行了一些乘法和加法,尽管我一直在阅读有关 Java 的 JIT 编译器的很酷的内容,但我还是有点失望。
首先 - 什么有效:执行许多乘以 1 似乎被简化并且执行得非常快:
tic();
final int nRepetitions = 100_000_000;
final double factor1 = 1.0d;
value = 0.0d;
for (int i=0;i<nRepetitions;i++) {
for (int j=0;j<20;j++) {
value = value * factor1;
}
}
System.out.println("Result = "+value);
toc();
Run Code Online (Sandbox Code Playgroud)
我得到这个执行速度,很快:
Result with graalvm-ce-17\bin\java.exe
----------------------
Repeating 100000000 multiplication by factor1 = 1.0, a final variable
The code is put in the main …Run Code Online (Sandbox Code Playgroud)