I'm wondering if the Java compiler will optimize the run of the for-loop if there no changes within the for-loop body?
For instance, let's suppose I have the following code:
double res = 0;
for (int i = 0; i < 1000; i++) {
res = calculateResValue();
}
Will the compiler shortcut the for-loop into a single calculateResValue() call?
I tried to modify the upper bound of the iteration counter, and I noticed that the time spent within for loop doesn't change proportionally to the boundary increase, i.e. let's suppose I run the loop not for 1000 times but 10000 times. I expect the timing to be increased in 10 times, but it doesn't happen.
calculateResValue()modifies some external state. Would you want it to be optimized away?Loop Invariant Code Motion. In this case, if a calculation within a loop doesn't change with each iteration, the compiler might move it outside. Have a look at the AI Overview -> typejava for loop compiler optimizationinto Google.