Will the expression "count limit" for-loop be evaluated only once or at each iteration?

If I call a method in a loop conditional, will it be called with each iteration of the loop?

For instance:

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

Will I execute expensiveComputation() on every iteration? Or will the result of expensiveComputation() be saved and used at each iteration, while the loop variable is initialized?

Should I instead rewrite it to this:

 int max = expensiveComputation(); for ( int i = 0; i <= max; i++ ) { // Do something. } 
+6
source share
4 answers

It will be called at each iteration if the compiler / optimizer does not decide that it has no side effects and can eliminate the call as an optimization.

I mean, the compiler cannot just blindly store the value, because a function in java, unlike a mathematical function, can have not only a return value, but also side effects such as printing something into some stream or change of any global state, etc.

There is another reason that the compiler cannot omit the call of each iteration. The fact that your function does not accept any arguments does not mean that it will necessarily return the same value each time. It can, for example, enter a number from a stream and return it, or it can randomly generate a number.

Therefore, the compiler must be very careful before it can safely eliminate calls. So, if a function is expensive, you should definitely keep its value.

+9
source

The second option is better, especially if the calculation does not require calculation at each iteration


If you assume your loop is n length, and you calculate O (n).
With the first solution, the complexity is O (n 2 ) and the other is O (2n)

+2
source

It may or may not be called at each iteration, depending on what bytecode the compiler feels like an emission. Most likely, it will be called every time.

If you want to make sure that it is not called at each iteration, use the version int max = ...

Why not just check it out yourself?

+2
source

Yes, you should cache your result in these situations in order to provide better performance.

+1
source

Source: https://habr.com/ru/post/896434/


All Articles