If I invoke a method within a loop’s conditional statement, will it be called with each loop iteration?
For example:
for( int i = 0; i <= expensiveComputation(); i++ ) {
// Do something.
}
Will I be performing expensiveComputation() on each iteration? Or will the result of expensiveComputation() be stored and used in each iteration at the same time the loop variable is initialised?
Should I instead re-write it to that:
int max = expensiveComputation();
for ( int i = 0; i <= max; i++ ) {
// Do something.
}
It will be invoked on each iteration, unless the compiler/optimizer decides that it has no side effects and can possibly eliminate the call as an optimization.
I mean, the compiler can’t just blindly store the value because a function in java, unlike a mathematical function, can have not only a return value, but also such side effects as printing something to some stream or changing some global state etc.
There is also another reason why the compiler can’t omit the call each iteration. The fact that your function doesn’t take any arguments does not mean that it will necessarily return the same value each time. It can, for example, input a number from a stream and return it, or it can randomly generate a number.
So the compiler needs to be extremely careful before it can safely eliminate the calls. So, if the function is expensive, you should definitely pre-store its value.