Is there a performance difference between i++ and ++i in C++?

前端 未结 17 2033
臣服心动
臣服心动 2020-11-21 17:15

We have the question is there a performance difference between i++ and ++i in C?

What\'s the answer for C++?

17条回答
  •  爱一瞬间的悲伤
    2020-11-21 18:06

    @Mark: I deleted my previous answer because it was a bit flip, and deserved a downvote for that alone. I actually think it's a good question in the sense that it asks what's on the minds of a lot of people.

    The usual answer is that ++i is faster than i++, and no doubt it is, but the bigger question is "when should you care?"

    If the fraction of CPU time spent in incrementing iterators is less than 10%, then you may not care.

    If the fraction of CPU time spent in incrementing iterators is greater than 10%, you can look at which statements are doing that iterating. See if you could just increment integers rather than using iterators. Chances are you could, and while it may be in some sense less desirable, chances are pretty good you will save essentially all the time spent in those iterators.

    I've seen an example where the iterator-incrementing was consuming well over 90% of the time. In that case, going to integer-incrementing reduced execution time by essentially that amount. (i.e. better than 10x speedup)

提交回复
热议问题