This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I would like to know if a for loop like the one that follows calls the array length once and then holds the value to check against for all its iterations, or if it calls the array length every time it loops through.
Hi Chris, It would have to call it each time. What if myarray is referenced to a different array inside the loop? Now that isn't to say that some optimizing slight of hand might take place to replace myarray.length if the context guaranteed that myarray would not change inside the block.
Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
It doesn't necesscarily call the array length everytime. This is a for loop, thus it is a counter loop. The loop will increment through the array's indexes until it reaches the array.length. Its just like putting the number 5 in there instead of array.length. Does this access the number 5 everytime? It does in a way. It simply checks to see if the int is smaller,larger,etc than that int value, but it does not parse the entire array. The for loop knows that this is just a number to be referenced by the initial int value.
The length variable here is a member of the array (kind of). As mentioned earlier, the array itself my change inside the loop, so yes the variable has to be evaluated every time. This is especially important to understand if you were to use a function call instead of a field name. In the case of a function, the function will be called EVERY time the loop iterates. If the function takes a lot of time, then this time factor is basically squared by the loop. I hope this makes some sense and answers your question. In short, yes the variable is accessed every time the loop iterates. Layne
It's easy to optimize this by hand to guarantee that no unnecessary lookup is performed each time thorough the loop:
That said, even if you don't do this and keep the loop in the form Chris originally showed, it's entirely possible that HotSpot could detect that (a) the .length attribute is a constant, and (b) myArray is never actually reassigned to another value inside the loop. In this case HotSpot could well optimize the loop to mirror the form I showed above. The chance of this occuring probably increases if myArray is declared as final. And it's also possible this optimization could be preformed by javac rather than HotSpot - but my impression is that Sun hasn't put that much effort into getting javac to optimize; there's much more benefit to putting effort into HotSpot. Of course, if the code does change myArray, as Michael showed, then these optimizations will not occur, and myArray.length must be looked up each time through the loop.