I've recently been reviewing code an noticed the use of this syntax in a for loop
for(int i = 0, len = myArray.length; i < len; i++){
//some code
}
as opposed to:
for(int i = 0; i < myArray.length; i++){
//some code
}
With the reasoning that it is more efficient as you don't have to keep looking up the myArray.length property with each loop.
I created a test to check if this was the case, and in all my tests the first for loop approach was significantly (around 70%) faster than the second.
I was curious why this syntax isn't more widely adopted and that i'm correct in thinking it is a better approach to using a for loop through an array.
This is a caching optimization, preventing, as you noted, many reads of length
. Frequently, it's not necessary to perform this kind of micro-optimization, which may explain why most engineers are happy to examine length
after each loop instead of caching it off, but it's useful in high-performance code. It can also be written like this, inverting the loop's direction and avoiding the use of another variable to hold the array's length:
for (int i = myArray.length - 1; i >= 0; i--) {
// some code
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With