【发布时间】:2013-04-18 19:43:27
【问题描述】:
我正在比较 Java 中嵌套 for、while 和 do-while 循环的效率,我遇到了一些奇怪的结果,需要帮助理解。
public class Loops {
public static void main(String[] args) {
int L = 100000; // number of iterations per loop
// for loop
double start = System.currentTimeMillis();
long s1 = 0;
for (int i=0; i < L; i++) {
for (int j = 0; j < L; j++) {
s1 += 1;
}
}
double end = System.currentTimeMillis();
String result1 = String.format("for loop: %.5f", (end-start) / 1000);
System.out.println(s1);
System.out.println(result1);
// do-while loop
double start1 = System.currentTimeMillis();
int i = 0;
long s2 = 0;
do {
i++;
int j = 0;
do {
s2 += 1;
j++;
} while (j < L);
} while (i < L);
double end1 = System.currentTimeMillis();
String result2 = String.format("do-while: %.5f", (end1-start1) / 1000);
System.out.println(s2);
System.out.println(result2);
// while loop
double start2 = System.currentTimeMillis();
i = 0;
long s3 = 0;
while (i < L) {
i++;
int j = 0;
while (j < L) {
s3 += 1;
j++;
}
}
double end2 = System.currentTimeMillis();
String result3 = String.format("while: %.5f", (end2-start2) / 1000);
System.out.println(s3);
System.out.println(result3);
}
}
所有循环各自的计数器总和为 100 亿;结果让我感到困惑:
for 循环:6.48300
执行时间:0.41200
而:9.71500
为什么 do-while 循环这么快?这种性能差距与对 L 的任何更改并行扩展。我已经独立运行这些循环并且它们执行相同。
【问题讨论】:
-
我无法复制您的号码。两个 while 循环对我来说运行速度相同,而 for 循环稍慢。
-
无论如何,这不是一个特别好的基准,因为编译器或 JIT 可能能够完全删除内部循环。
-
必须是这种情况 - 某种只在 do-while 循环中执行的优化。不过,我很想了解更多关于这种机制的信息。
-
是的,我不太清楚这里发生了什么。我更像是一个 C 和 C++ 人,我几乎没有深入研究 JVM/JIT 怪异的经验。
标签: java performance for-loop while-loop do-while