Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In for loops, does the length of the array get evaluated each iteration?

Tags:

java

if I have a for loop like...

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

...does myArray.lengthget evaluated every iteration? So would something like...

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

... be a small performance increase?

like image 930
jtht Avatar asked Jan 14 '15 00:01

jtht


People also ask

How many times does a for loop iterate through an array?

The classic and famous for loop iterates over each item in the array. The for loops through a block of code a number of times: The for uses 3 expressions: Initialization - initializes the loop variable with a starting value which can only be executed once.

What is the exception to looping over an array in Java?

The one exception to this rule is looping over an array where the constraint is the Length. The CLR JIT will special case this type of loop, in certain circumstances, since the length of an array can't change.

How do you USE FOR loop in an array?

The classic and famous for loop iterates over each item in the array. The for loops through a block of code a number of times: let arr = [ 1, 2, 3, 4, 5 ]; for ( let i = 0; i < arr.length; i++) { console .log (arr [i]); } The for uses 3 expressions:

How do you do a for each loop in Java?

For-each loop in Java It starts with the keyword for like a normal for-loop. Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name.


2 Answers

regardless myArray.length is just a field so there is nothing to evaluate

Java array has length as public final int so it gets initialized once and when you refer to it there is no code execution like a method call

The public final field length, which contains the number of components of the array. length may be positive or zero.

like image 194
jmj Avatar answered Sep 21 '22 10:09

jmj


The first form will probably incur some performance penalty, since evaluating it will require, before the iflt, an aload, an arraylength and an iload; whereas the second is only two iloads.

@ajp rightly mentions that myArray may change; so it is highly unlikely that the compiler will optimize the first form into the second for you (unless, maybe, myArray is final).

However, the JIT, when it kicks in, is probably smart enough so that, if myArray doesn't change, it will turn the first form into the second.

Just in case, anyway, use the second form (this is what I always do, but that's just out of habit). Note that you can always javap the generated class file to see the generated byte code and compare.


By the way, Wikipedia has a very handy page listing all of a JVM's bytecodes. As you may see, quite a lot of them are dedicated to arrays!

like image 29
fge Avatar answered Sep 23 '22 10:09

fge