7

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?

Community
  • 1
  • 1
dafrad
  • 71
  • 1
  • 2
  • Duplicate: http://stackoverflow.com/questions/2020184/preincrement-faster-than-postincrement-in-c-true-if-yes-why-is-it (et al) – gregg Mar 07 '11 at 19:21

2 Answers2

13

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.

AnT
  • 302,239
  • 39
  • 506
  • 752
  • 2
    A good optimizer can often remove the copying of the old value, especially if it is not used. So "slower" should probably be "not faster". – Bo Persson Mar 07 '11 at 19:46
  • @Bo Persson: That's why I said "generally". – AnT Mar 07 '11 at 19:48
  • 1
    No, you said "generally slower", I said "generally not faster". :-). The question is: Why use post increment if it is not faster? No reason! – Bo Persson Mar 07 '11 at 19:59
  • 5
    "Not faster" would not need "generally". Post-increment is not faster. Post-increment is generally slower. – AnT Mar 07 '11 at 21:31
7

You can see in this Example that was created a temp, in postfix... This more slowly than prefix, where is no created advanced object

// Define prefix increment operator.
Point& Point::operator++()
{
   _x++;
   _y++;
   return *this;
}

// Define postfix increment operator.
Point Point::operator++(int)
{
   Point temp = *this;
   ++*this;
   return temp;
}

++iter more faster than iter++., because don't created copy of object

Bhargav Rao
  • 45,811
  • 27
  • 120
  • 136
G-71
  • 3,476
  • 12
  • 44
  • 67