Can end() be a costly operation for stl containers

后端 未结 7 1960
囚心锁ツ
囚心锁ツ 2020-12-16 12:16

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         


        
7条回答
  •  轮回少年
    2020-12-16 12:25

    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.

提交回复
热议问题