为什么跳过 for 循环?

Shu*_*ham 3 java jvm

long start = System.currentTimeMillis();
long m = 0;
System.out.println("Going into the loop");

for (int i = 0; i < 10000000; i++) {
    for (int j = 0; j < 1000; j++) {
        if (i % 2 == 0 && j % 3 == 0) {
            m = i + j;
        }
    }
}

System.out.println("Out of the loop");

long end = System.currentTimeMillis();
System.out.println("Time : " + (end - start));
System.out.println("m : " + m);
Run Code Online (Sandbox Code Playgroud)

当我运行上面的代码时,“m”的值评估为 10000997,运行时间为 13321。

Going into the loop
Out of the loop
Time : 13321
m : 10000997
Run Code Online (Sandbox Code Playgroud)

但是当我评论最后一个打印“m”值的 SOP 语句时,运行时间大约为 7。

Going into the loop
Out of the loop
Time : 7
Run Code Online (Sandbox Code Playgroud)

那么为什么会发生这种情况呢?是否跳过了 for 循环?

Nic*_*tar 7

编译器优化您的代码并意识到变量 m 实际上是一个可以删除的死存储。然后它意识到 if 根本不做任何事情(在 m 被删除之后)并且也删除了它。ineer 循环和外循环也是如此。

  • 注意:这是 JIT 编译器执行的操作,而不是 javac。 (3认同)
  • 进一步注意,它不必按字面意思工作。一般来说,它可以通过从结果值和可感知的副作用到获取必要值所需的操作遍历图表来工作,有效地跳过不需要的所有内容,甚至无需查看它。这取决于内部 IR 的设计方式。 (2认同)