++i bit more efficient due to its semantics:
++i; // Fetch i, increment it, and return it i++; // Fetch i, copy it, increment i, return copy
For indices of type int, the gain of efficiency is minimal (if any). For iterators and other objects with a heavier weight, avoiding this copy can be a real gain (especially if the loop body does not contain a lot of work).
As an example, consider the following cycle, using the theoretical BigInteger class, which provides arbitrary precision integers (and, therefore, some vector objects):
std::vector<BigInteger> vec; for (BigInteger i = 0; i < 99999999L; i++) { vec.push_back(i); }
This i ++ operation involves building a copy (i.e. a new operator, a digital copy) and destroying (deleting the operator) for a loop that will do nothing but essentially make another copy of the index object. Essentially, you doubled the work you are doing (and most likely increased memory fragmentation) by simply using a postfix increment where the prefix would be sufficient.
Drew Hall Nov 23 '10 at 22:41 2010-11-23 22:41
source share