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


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

What's the answer for C++?

9/12/2016 5:41:01 AM

Accepted Answer

[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
    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.

3/29/2018 8:08:56 PM

Yes. There is.

The ++ operator may or may not be defined as a function. For primitive types (int, double, ...) the operators are built in, so the compiler will probably be able to optimize your code. But in the case of an object that defines the ++ operator things are different.

The operator++(int) function must create a copy. That is because postfix ++ is expected to return a different value than what it holds: it must hold its value in a temp variable, increment its value and return the temp. In the case of operator++(), prefix ++, there is no need to create a copy: the object can increment itself and then simply return itself.

Here is an illustration of the point:

struct C
    C& operator++();      // prefix
    C  operator++(int);   // postfix


    int i_;

C& C::operator++()
    return *this;   // self, no copy created

C C::operator++(int ignored_dummy_value)
    C t(*this);
    return t;   // return a copy

Every time you call operator++(int) you must create a copy, and the compiler can't do anything about it. When given the choice, use operator++(); this way you don't save a copy. It might be significant in the case of many increments (large loop?) and/or large objects.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow