javaarrayspremature-optimization

What is the Cost of Calling array.length


While updating for loops to for-each loops in our application, I came across a lot of these "patterns":

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

instead of

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

I can see that you gain performance for collections because you don't need to call the size() method with each loop. But with arrays??

So the question arose: is array.length more expensive than a regular variable?


Solution

  • 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.

    1. if you are debugging the enclosing method, or
    2. if the loop body has enough local variables to force register spilling.