Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a variable in a for loop for the array length [duplicate]

Tags:

java

for-loop

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.

like image 652
Loco234 Avatar asked Apr 28 '15 10:04

Loco234


1 Answers

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
}
like image 77
Chris Mantle Avatar answered Oct 13 '22 19:10

Chris Mantle