为什么跳过 for 循环?
Why are the for loops skipped?
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);
当我 运行 上面的代码然后 "m" 的值评估为 10000997 并且 运行ning 时间是 13321.
Going into the loop
Out of the loop
Time : 13321
m : 10000997
但是当我评论打印 "m" 值的最后一个 S.O.P 语句时,运行ning 时间大约是 7.
Going into the loop
Out of the loop
Time : 7
那么为什么会这样呢?是否跳过了 for 循环?
编译器优化您的代码并意识到变量 m 实际上是一个可以删除的死存储。然后它意识到 if 根本不做任何事情(在删除 m 之后)并且也将其删除。内循环和外循环也是如此。
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);
当我 运行 上面的代码然后 "m" 的值评估为 10000997 并且 运行ning 时间是 13321.
Going into the loop
Out of the loop
Time : 13321
m : 10000997
但是当我评论打印 "m" 值的最后一个 S.O.P 语句时,运行ning 时间大约是 7.
Going into the loop
Out of the loop
Time : 7
那么为什么会这样呢?是否跳过了 for 循环?
编译器优化您的代码并意识到变量 m 实际上是一个可以删除的死存储。然后它意识到 if 根本不做任何事情(在删除 m 之后)并且也将其删除。内循环和外循环也是如此。