Will the “count limit” expression of the Java – for loop be evaluated only once, or each iteration?

If I call the method in the conditional statement of the loop, do I call it at every iteration of the loop?

For example:

for( int i = 0; i <= expensivecomputation(); i++ ) {
    // Do something.
}

Will I perform expensive computation () in each iteration? Or, will the results of expensivecomputation () be stored and used in each iteration while the loop variable is initialized?

I should rewrite it:

int max = expensivecomputation();
for ( int i = 0; i <= max; i++ ) {
    // Do something.
}

Solution

Unless the compiler / optimizer determines that it has no side effects and may eliminate the call as an optimization, it will be called at each iteration

I mean, the compiler can't store this value blindly, because unlike mathematical functions, functions in Java can not only have return values, but also have the side effects of printing some content to a stream or changing some global state

There is another reason why the compiler cannot omit calls at each iteration The fact that your function does not accept any parameters does not mean that it must return the same value every time For example, it can enter a number from the stream and return it, or it can generate a number at random

Therefore, the compiler needs to be very careful before safely eliminating calls Therefore, if the function is expensive, you must store its value in advance

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>