Incrementing iterators: Is ++it more efficient than it++? [duplicate]

The reason behind the preincrement being faster is that post-increment has to make a copy of the old value to return. As GotW #2 put it, “Preincrement is more efficient than postincrement, because for postincrement the object must increment itself and then return a temporary containing its old value. Note that this is true even for builtins like int.”

GotW #55 provides the canonical form of postincrement, which shows that it has to do preincrement plus some more work:

T T::operator++(int)
{
  T old( *this ); // remember our original value
  ++*this;        // always implement postincrement
                  //  in terms of preincrement
  return old;     // return our original value
}

As others have noted, it’s possible for some compiler to optimize this away in some cases, but if you’re not using the return value it’s a good idea not to rely on this optimization. Also, the performance difference is likely to be very small for types which have trivial copy constructors, though I think using preincrement is a good habit in C++.

Leave a Comment