Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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++?

like image 426
Mark Harrison Avatar asked Aug 24 '08 07:08

Mark Harrison


People also ask

What is faster i ++ or ++ i?

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

Is ++ i or i ++ more efficient?

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

What is the difference between -- I and I --?

There is no difference in your case. --i is pre-decrement and i-- is post-decrement.

What is faster ++ i or i ++ where i is an integer variable?

In C++ the faster is ++i; due to its object. However some compilers may optimize the post-increment operator.


1 Answers

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

like image 91
Mark Harrison Avatar answered Oct 14 '22 04:10

Mark Harrison