我的理解是增强型for循环应该更慢,因为它们必须使用迭代器。但是我的代码提供了不同的结果。(是的,我知道循环逻辑占用了循环大部分时间)
对于较少的迭代次数(100-1000),增强型for循环似乎比传统for循环快得多,无论有没有启用JIT编译。相反,当迭代次数很高(100000000)时,传统的循环要快得多。到底发生了什么?
public class NewMain {
public static void main(String[] args) {
System.out.println("Warming up");
int warmup = 1000000;
for (int i = 0; i < warmup; i++) {
runForLoop();
}
for (int i = 0; i < warmup; i++) {
runEnhancedFor();
}
System.out.println("Running");
int iterations = 100000000;
long start = System.nanoTime();
for (int i = 0; i < iterations; i++) {
runForLoop();
}
System.out.println((System.nanoTime() - start) / iterations + "nS");
start = System.nanoTime();
for (int i = 0; i < iterations; i++) {
runEnhancedFor();
}
System.out.println((System.nanoTime() - start) / iterations + "nS");
}
public static final List<Integer> array = new ArrayList(100);
public static int l;
public static void runForLoop() {
for (int i = 0; i < array.size(); i++) {
l += array.get(i);
}
}
public static void runEnhancedFor() {
for (int i : array) {
l += i;
}
}
}
System.nanoTime()
,它不可靠。 - Elliott Frisch