Function call for loop condition?

If I have a call in function for a loop condition, for example:

for (auto it = s.begin(); it != s.end(), ++it) {} 

is it called at each iteration? I expect yes. Can the compiler optimize it? Are modern compilers smart enough? Or am I better off using something like the following:

 for (auto it = s.begin(), auto end = s.end(); it != end; ++it) {} 

?

+5
source share
3 answers

Yes, the program should call the second expression it != s.end() at each iteration. I think the compiler can optimize this in a specific situation.

In any case, do not do compiler work. If it can be optimized, there is a good chance that the compiler is already doing this, and in any case this call does not have a significant performance improvement.

If your case resolves this, you should use a loop based range:

 for (auto& i : s) { // instructions } 

Thus, the compiler has even more options for optimizing your code and is easier to read.

If you need an example of how much the compiler can optimize the material, look at that! http://ridiculousfish.com/blog/posts/will-it-optimize.html

+4
source

IN

 for ( auto it = s.begin(); it != s.end(), ++it ) 

s.begin() is called only once.
s.end() and operator++() (for ++it ) are called at each iteration of the loop.

Can the compiler optimize it?

The compiler may optimize the s.end() call depending on the compiler, implementation, and level of optimization. I will be surprised if he can optimize the operator++() call.

Are current compilers smart enough for this?

I can not answer this question.

Or am I better off using something like the following:

 for (auto it = s.begin(), auto end = s.end(); it != end; ++it) {} 

It will not hurt. However, this can be a problem if s modified in a loop. If s not changed in the loop, I would recommend using this approach.

+6
source

Yes, this is formally called at every iteration. And yes, current compilers are likely to inline the function and see that s.end() returns the same value each time (pointer?).

You do not need to complicate the code if profiling does not show that this is a bottleneck in your program (extremely unlikely).

+1
source

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


All Articles