When replacing for loops with for-each loops, developers often encounter the following pattern:
<code class="java">for (int i = 0, n = a.length; i < n; i++) { ... }</code>
Instead of the simpler:
<code class="java">for (int i = 0; i < a.length; i++) { ... }</code>
This raises the question: is the extra n = a.length assignment a performance hit for arrays?
No, a call to array.length is an O(1) or constant time operation.
The .length property of an array is a public final member, and accessing it is no slower than a local variable. This is unlike method calls like size(), which typically involve more overhead.
Modern JIT compilers can also optimize the call to .length to eliminate it entirely. To verify this, one can inspect the source code of the JIT compiler or examine the dumped native code.
However, the JIT compiler may not always be able to perform this optimization, such as when debugging is enabled or when the loop body contains excessive local variables.
The above is the detailed content of ## Is Calling `array.length` in a for Loop a Performance Bottleneck?. For more information, please follow other related articles on the PHP Chinese website!