if I have a for loop like...
for (int i = 0; i < myArray.length; i++) { ... }
...does myArray.length
get evaluated every iteration? So would something like...
int len = myArray.length;
for (int i = 0; i < len; i++) { ... }
... be a small performance increase?
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.
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.
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:
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.
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.
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 iload
s.
@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!
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