1

I've read historically that pre-increment is faster/better for a variety of reasons (and also that it should be moot on modern compilers). But isn't there additional processing required for the copy process when objects come into play?

For example:

iterator iterator::operator++(
   int)
{
   iterator copy(*this);
   _index++;

   return copy;
}

iterator& iterator::operator++() {
   _index++;

   return *this;
}

The pre-increment operator needs a copy operation. So simply doing this should be slower:

loop {
--object
}

Does the philosophy of "pre vs post" only apply to primitives?

Zhro
  • 2,546
  • 2
  • 29
  • 39
  • Post-increment needs a copy, pre-increment doesn't. Not really an issue for PODs but for classes copies may be expensive. It's hard to tell what else you're asking, sorry. – Jonathan Potter Jan 30 '16 at 01:00

1 Answers1

1

For exactly the reason you've described it's generally considered good practice to use preincrement and predecrement on iterators. A good optimizing compiler might be able to remove the unnecessary copy, but you can't guarantee this.

As for whether actual preincrement and postincrement are still faster or slower for primitives, that advice has likely been incorrect for at least a decade. Optimizing compilers are really good at spotting unnecessary copies or operations and I'd be amazed if they couldn't figure out not to make an unnecessary copy.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065