Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

c++ - Can end() be a costly operation for stl containers

On https://doc-snapshots.qt.io/qtcreator-extending/coding-style.html it is recommended to write for loops like the following:

Container::iterator end = large.end();
for (Container::iterator it = large.begin(); it != end; ++it) {
        //...;
}

instead of

for (Container::iterator it = large.begin(); it != large.end(); ++it) {
        //...;
}

Since I have rarely seen this style in any code, I would like to know whether the consecutive call of end() really adds a noticeable run-time overhead for large loops over stl containers or whether compilers already optimize such cases.

Edit: As many of to very good comments pointed out: This question is only valid if the code inside the loop does not modify the end iterator. Otherwise of course the repeated call of end is mandatory.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The C++11 standard (§ 23.2.1) mandates that end has O(1) complexity, so a conforming implementation would have the same performance characteristics for both versions.

That said, unless the compiler can prove that the return value of end will never change then pulling end out of the loop might be faster by some constant quantity (as Steve Jessop comments, there are lots of variables that can influence whether this is true or not).

Still, even if in one particular case there is absolutely no performance difference, pulling such tests out of the loop is a good habit to get into. An even better habit to get into is to utilize standard algorithms as @pmr says, which sidesteps the issue entirely.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...