我和我的朋友都被难住了。在这两个代码块中,为什么第一个内循环比第二个内循环快?这是某种 JVM 优化吗?
public class Test {
public static void main(String[] args) {
int[] arr = new int[100000000];
arr[99999999] = 1;
long t1, t2, t3;
for (int ndx = 0; ndx < 10; ndx++) {
t1 = System.currentTimeMillis();
for (int i = 0; i < arr.length; i++)
if (0 < arr[i])
System.out.print("");
t2 = System.currentTimeMillis();
for (int i = 0; i < arr.length; i++)
if (arr[i] > 0)
System.out.print("");
t3 = System.currentTimeMillis();
System.out.println(t2 - t1 +" "+(t3 - t2));
}
}
}
结果:
me@myhost ~ $ java Test
57 80
154 211
150 209
149 209
150 209
150 209
151 209
150 210
150 210
149 209
交换不等式的顺序:
public class Test {
public static void main(String[] args) {
int[] arr = new int[100000000];
arr[99999999] = 1;
long t1, t2, t3;
for (int ndx = 0; ndx < 10; ndx++) {
t1 = System.currentTimeMillis();
for (int i = 0; i < arr.length; i++)
if (arr[i] > 0)
System.out.print("");
t2 = System.currentTimeMillis();
for (int i = 0; i < arr.length; i++)
if (0 < arr[i])
System.out.print("");
t3 = System.currentTimeMillis();
System.out.println((t2 - t1) +" "+(t3 - t2));
}
}
}
结果:
me@myhost ~ $ java Test
56 80
155 210
150 209
149 209
151 210
149 209
150 209
149 208
149 209
149 208
精神错乱:一遍又一遍地做同样的事情并得到不同的结果。