/ 猿问

调用array.length的成本是多少

2019-08-19 17:16:56

```for (int i = 0, n = a.length; i < n; i++) {
...}```

```for (int i = 0; i < a.length; i++) {
...}```

3 回答

1. 如果您正在调试封闭方法，或者

2. 如果循环体有足够的局部变量来强制寄存器溢出。

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

250000000因为我得到了OutOfMemoryError，所以我不能做得更大270000000。

• 3 回答
• 0 关注
• 237 浏览

0/150