Performance difference between ++iterator and iterator++?

后端 未结 7 1075
悲哀的现实
悲哀的现实 2020-12-08 04:32

My workmate claims that for object types preincrement is more efficient than post increment

e.g.

std::vector vec;

... insert a wh         


        
7条回答
  •  隐瞒了意图╮
    2020-12-08 05:25

    Seriously, unless you're actually having performance problems due to calling post-increment instead of pre-increment THE PERFORMANCE DIFFERENCE WILL ONLY MATTER IN VERY RARE CIRCUMSTANCES.


    Update

    For instance, if your software is a climate simulation, and operator++ causes the simulation to move forward a step (that is ++simulation gives you the next step in the simulation, while simulation++ makes a copy of the current step in the simulation, advances the simulation, and then hands you the copy) then performance will be an issue.

    More realistically, in a comment, the original questioner mentions that we're discussing an embedded project with (apparently) real time requirements. In that case you need to actually look at your specific implementation. I seriously doubt that you'll have noticeable slowdowns iterating through a std::vector with post-increment instead of pre-increment, although I haven't benchmarked any STL implementation on this matter.


    Don't pick one over the other for performance reasons. Pick one over the other for clarity/maintenance reasons. Personally I default to pre-increment because I generally don't give a damn what the value was before incrementing.

    If your brain blows up when you see ++i instead of i++ it may be time to consider going into a different line of work.

提交回复
热议问题