Why is ++i more efficient than i++?
c++, do-while, for-loop, while-loop
Solution
`i++` increments `i` and returns the initial value of `i`. Which means:
int i = 1;
i++; // == 1 but i == 2
But `++i` returns the actual incremented value:
int i = 1;
++i; // == 2 and i == 2 too, so no need for a temporary variable
In the first case, the compiler has to create a temporary variable (when used) for returning `1` instead of `2` (in the case where it's not a constant of course but a dynamic value, a return from a call for example).
In the second case, it does not have to. So the second case is guaranteed to be at least as effective.
Often, the compiler will be able to optimize the first case into the second case, but sometimes it may not be able to.
Anyway, we're talking about highly negligible impact.
But on more complicated objects such as `iterators`-like objects, having a temporary state may be pretty slower if iterated millions of times.
Rule of thumb
Use prefix version unless you specifically want the postfix semantics.
Problem
According to the Google C++ Style Guide, "when the return value is ignored, the 'pre' form (`++i`) is never less efficient than the 'post' form (`i++`), and is often more efficient." The guide goes on to explain why, but I don't exactly understand. Thoughts? Perhaps someone could provide an example of this concept?