When replacing for loops with for-each loops, developers often encounter the following pattern:
for (int i = 0, n = a.length; i Instead of the simpler:
for (int i = 0; i This raises the question: is the extra n = a.length assignment a performance hit for arrays?
The Answer
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3