R
Rhino
Given a loop like this:
for (int ix=0; ix<myArray.length; ix++) {
System.out.println(ix);
}
or especially this:
for (int ix=0; ix<Math.sqrt(shoeSize)*hairlength/(IQ); ix++) {
System.out.println(ix);
}
I've always assumed that it made more sense calculate the
"loop controller" value in the second term of the for loop (sorry, I forget
the proper name), rather than make Java look it up
or calculate it, especially for large numbers of iterations of the loop. It
just made no sense to do the same calculation or lookup a thousand or a
million times; it seemed a lot more reasonable to do the calculation or
lookup ONCE, store the value in a variable, and then plug the variable into
the for loop, like this:
int loopController = Math.sqrt(shoeSize)*hairlength/(IQ);
for (int ix=0; ix<loopController; ix++) {
System.out.println(ix);
}
Is my reasoning sound or does Java have "tricks" (optimizations) that make
it more sensible to leave the lookup or calculation in the loop, thus
avoiding the need to create the variable that controls the loop?
I've been wondering about that for a while and am finally getting around to
asking ;-)
I realize that I could set up a benchmark to find out for sure but I'm
betting that the answer is already well-known so I'd rather ask here and
save myself the work ;-)
for (int ix=0; ix<myArray.length; ix++) {
System.out.println(ix);
}
or especially this:
for (int ix=0; ix<Math.sqrt(shoeSize)*hairlength/(IQ); ix++) {
System.out.println(ix);
}
I've always assumed that it made more sense calculate the
"loop controller" value in the second term of the for loop (sorry, I forget
the proper name), rather than make Java look it up
or calculate it, especially for large numbers of iterations of the loop. It
just made no sense to do the same calculation or lookup a thousand or a
million times; it seemed a lot more reasonable to do the calculation or
lookup ONCE, store the value in a variable, and then plug the variable into
the for loop, like this:
int loopController = Math.sqrt(shoeSize)*hairlength/(IQ);
for (int ix=0; ix<loopController; ix++) {
System.out.println(ix);
}
Is my reasoning sound or does Java have "tricks" (optimizations) that make
it more sensible to leave the lookup or calculation in the loop, thus
avoiding the need to create the variable that controls the loop?
I've been wondering about that for a while and am finally getting around to
asking ;-)
I realize that I could set up a benchmark to find out for sure but I'm
betting that the answer is already well-known so I'd rather ask here and
save myself the work ;-)