We have the question is there a performance difference between i++
and ++i
in C?
What's the answer for C++?
++i is sometimes faster than, and is never slower than, i++. 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.
According to the Google C++ Style Guide, "when the return value is ignored, the 'pre' form ( ++i ) is never less efficient than the 'post' form ( i++ ), and is often more efficient."
There is no difference in your case. --i is pre-decrement and i-- is post-decrement.
In C++ the faster is ++i; due to its object. However some compilers may optimize the post-increment operator.
[Executive Summary: Use ++i
if you don't have a specific reason to use i++
.]
For C++, the answer is a bit more complicated.
If i
is a simple type (not an instance of a C++ class), then the answer given for C ("No there is no performance difference") holds, since the compiler is generating the code.
However, if i
is an instance of a C++ class, then i++
and ++i
are making calls to one of the operator++
functions. Here's a standard pair of these functions:
Foo& Foo::operator++() // called for ++i { this->data += 1; return *this; } Foo Foo::operator++(int ignored_dummy_value) // called for i++ { Foo tmp(*this); // variable "tmp" cannot be optimized away by the compiler ++(*this); return tmp; }
Since the compiler isn't generating code, but just calling an operator++
function, there is no way to optimize away the tmp
variable and its associated copy constructor. If the copy constructor is expensive, then this can have a significant performance impact.
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