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?
No, a call to
array.lengthisO(1)or constant time operation.Since the
.lengthis(acts like) apublicfinalmember ofarray, it is no slower to access than a local variable. (It is very different from a call to a method likesize())A modern JIT compiler is likely to optimize the call to
.lengthright 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.