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++){
Unlike:
for(int i = 0; i < myArray.length; i++){
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.
java for-loop
Loco234
source share