Possible Duplicates:
Preincrement faster than postincrement in C++ - true? If yes, why is it?
Is there a performance difference between i++ and ++i in C++?
I got told that when using the STL and it's iterators, I should always use ++iter
instead of iter++
.
I quote:
Because it can only be faster, never slower
Is this true?
Pre-increment is faster than post-increment because post increment keeps a copy of previous (existing) value and adds 1 in the existing value while pre-increment is simply adds 1 without keeping the existing value.
For intrinsic types like int, it doesn't matter: ++i and i++ are the same speed. For class types like iterators or the previous FAQ's Number class, ++i very well might be faster than i++ since the latter might make a copy of the this object.
As a result, pre-increment is faster than post-increment because post-increment keeps a copy of the previous value where pre-increment directly adds 1 without copying the previous value.
In C it is the same. In C++ the faster is ++i; due to its object. However some compilers may optimize the post-increment operator.
Yes. It is true in general. The postfix increment is burdened with the task of preserving and returning the old value of the iterator. That takes time and effort, which is what generally makes it slower.
It is generally true for all overloaded increment/decrement operators that implement the traditional pre/post semantics.
This topic is beaten to death. Do a search here on "prefix postfix" for a large number of more detailed explanations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With