Variable declaration in a for loop for array length

I recently looked at the code, noticed that using this syntax in a for loop

for(int i = 0, len = myArray.length; i < len; i++){ //some code } 

Unlike:

 for(int i = 0; i < myArray.length; i++){ //some code } 

Given that it is more efficient, since you do not need to constantly search for 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 approach to the cycle was significantly (about 70%) faster than the second.

I was curious why this syntax is not more widely accepted and that I am right in thinking that this is the best approach to using a for loop through an array.

+7
java for-loop
source share
3 answers

This is a cache optimization that prevents, as you have noticed, many length readings. Often there is no need to perform such micro-optimization, which may explain why most engineers are happy to consider length after each cycle and not cache it, but this is useful in high-performance code. It can also be written this way, inverting the direction of the loop and avoiding the use of another variable to store the length of the array:

 for (int i = myArray.length - 1; i >= 0; i--) { // some code } 
+5
source share

The first approach estimates the length only once instead of the second, where the length is estimated by each cycle.

0
source share

In my opinion, most Java programmers use a for-each loop in the case of arrays, if we do not want to do some index manipulation

0
source share

All Articles