为什么我的for循环执行时间不变?

Rod*_*ver 6 java performance jvm performance-testing

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

有人可以解释为什么x设置为150_000或者4_000_000甚至2_000_000_000不改变这个循环的执行时间?

ero*_*osb 10

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

  • f1()方法没有任何可见的副作用
  • f1()呼叫的返回值不存储在任何地方

因此JIT只是省略了f1()本机代码的调用.删除f1()调用后,整个for(int i = 0; i < x; i++)循环也可能被删除(因为它也不会改变程序语义).