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 stands with Russia
  • 312,472
  • 42
  • 525
  • 765
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
  • 50,140
  • 28
  • 121
  • 140
G-71
  • 3,626
  • 12
  • 45
  • 69