为什么我的 for 循环执行时间没有改变?

Why is my for loop execution time not changing?

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_0004_000_000 甚至 2_000_000_000 不会改变此循环的执行时间吗?

在执行期间,JVM 的即时 (JIT) 编译器将 java 字节码(class 格式)编译为您机器的本机指令集。 JIT 在编译期间执行多项优化。在这种情况下,JIT 可能实现了以下内容(只是猜测):

  • f1() 方法没有任何可见的副作用
  • f1() 调用的 return 值未存储在任何地方

因此 JIT 简单地从本机代码中省略了 f1() 调用。有可能在移除 f1() 调用后,整个 for(int i = 0; i < x; i++) 循环也被移除(因为它也不会改变程序语义)。