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 循环?
编译器优化您的代码并意识到变量 m 实际上是一个可以删除的死存储。然后它意识到 if 根本不做任何事情(在 m 被删除之后)并且也删除了它。ineer 循环和外循环也是如此。
| 归档时间: |
|
| 查看次数: |
102 次 |
| 最近记录: |