Postfix increment and decrement operators create a temporary object when used while prefix operators don’t.
It is therefore more efficient to use the prefix version where possible, particularly in for loop constructs as whatever is used will be called multiple times in that case, i.e.,
In addition to the good answer so far, a few additional remarks can be made.
In loop constructions using integral counters, then all good compilers will put the loop counter in a register or on the stack. The counter will be properly initialized and incremented once upon every trip through the loop in each case at the end of the loop before the assembler instruction for the loop-end comparison. For these simple cases, there will be no performance differences between the two incrementing orders.
However, for complex types with specialized pre-increment and post-increment operators, the performance issues can be significant.
Sincerely, Chris.
You're gonna go blind staring into that box all day.
Small point: if you implement postfix ++ (and --) in terms of prefix, you only need to make modifications in one place:
Code:
c operator++(int) // posfix
{
c old = *this;
operator++();
return old;
}
Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
-- Sutter and Alexandrescu, C++ Coding Standards
Programs must be written for people to read, and only incidentally for machines to execute.
-- Harold Abelson and Gerald Jay Sussman
The cheapest, fastest and most reliable components of a computer system are those that aren't there. -- Gordon Bell
Bookmarks