public class Test {
public static void main(String[] args) {
int x = 150_000;
long start = System.currentTimeMillis();
for(int i = 0; i < x; i++) {
f1(i);
}
long end = System.currentTimeMillis();
System.out.println((end - start) / 1000.0);
}
private static long f1(int n) {
long x = 1;
for(int i = 0; i < n; i++) {
x = x + x;
}
return x;
}
}
有人可以解释为什么将 x 设置为 150_000
或 4_000_000
甚至 2_000_000_000
不会改变此循环的执行时间吗?
最佳答案
在执行期间,JVM 的即时 (JIT) 编译器将 java 字节码(类格式)编译为您机器的 native 指令集。 JIT 在编译期间执行多项优化。在这种情况下,JIT 可能意识到以下内容(只是猜测):
f1()
方法没有任何可见的副作用-
f1()
的返回值通话未存储在任何地方
因此 JIT 简单地省略了 f1()
从 native 代码调用。删除 f1()
后可能调用整个 for(int i = 0; i < x; i++)
循环也已被删除(因为它也不会改变程序语义)。
关于java - 为什么我的 for 循环执行时间没有改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33083111/