What is the Cost of Calling array.length
I had a bit of time over lunch:
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));
}
}
The results:
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
Notes:
- If you reverse the tests, then
n = a.length
shows as being faster thani < a.length
by about half, probably due to garbage collection(?). - I couldn't make
250000000
much larger because I gotOutOfMemoryError
at270000000
.
The point is, and it is the one everyone else has been making, you have to run Java out of memory and you still don't see a significant difference in speed between the two alternatives. Spend your development time on things that actually matter.
No, a call to array.length
is O(1)
or constant time operation.
Since the .length
is(acts like) a public
final
member of array
, it is no slower to access than a local variable. (It is very different from a call to a method like size()
)
A modern JIT compiler is likely to optimize the call to .length
right out anyway.
You can confirm this by either looking at the source code of the JIT compiler in OpenJDK, or by getting the JVM to dump out the JIT compiled native code and examining the code.
Note that there may be cases where the JIT compiler can't do this; e.g.
- if you are debugging the enclosing method, or
- if the loop body has enough local variables to force register spilling.