我在午餐时有一点时间:
public static void main(String[] args) {
final int[] a = new int[250000000];
long t;
for (int j = 0; j < 10; j++) {
t = System.currentTimeMillis();
for (int i = 0, n = a.length; i < n; i++) { int x = a[i]; }
System.out.println("n = a.length: " + (System.currentTimeMillis() - t));
t = System.currentTimeMillis();
for (int i = 0; i < a.length; i++) { int x = a[i]; }
System.out.println("i < a.length: " + (System.currentTimeMillis() - t));
}
}
结果:
n = a.length: 672
i < a.length: 516
n = a.length: 640
i < a.length: 516
n = a.length: 656
i < a.length: 516
n = a.length: 656
i < a.length: 516
n = a.length: 640
i < a.length: 532
n = a.length: 640
i < a.length: 531
n = a.length: 641
i < a.length: 516
n = a.length: 656
i < a.length: 531
n = a.length: 656
i < a.length: 516
n = a.length: 656
i < a.length: 516
笔记:
- 如果你逆转测试,那么显示比大约一半快,可能是由于垃圾回收(?)。
n = a.length
i < a.length
- 我不能做得更大,因为我得到了.
250000000
OutOfMemoryError
270000000
关键是,这是其他人一直在做的,你必须在内存中运行Java,你仍然看不到两种选择之间在速度上的显着差异。将开发时间花在真正重要的事情上。