September 29, 2006
Which is faster, i++ or ++i?
The answer is that you're probably asking the wrong question--for two reasons.
The first reason that it's the wrong question is that such questions concern only micro-performance: Does the statement take one machine cycle, or two, or whatever. Questions about micro-performance often depend strongly on implementation details, which means you can't really know the answers without measuring them as part of the overall application.
The second reason that it's the wrong question is that you would usually be better asking which usage is a better fit for your problem. For example, if you are asking about
for (int i = 0; i != n; i++) {/* do something */ }
the answer is that you are better off using ++i than i++, but not for any reasons of efficiency. Rather, when you write i++, you are directing that the value of i be copied, then incremented, and then the copy thrown away. There is no reason to make that copy in the first place, so why specify it?
As yet another example, if it is an iterator and M is a map, then writing
M.erase(it++);
is by far the most succinct way of erasing the element to which it refers while leaving it referring to the position immediately after the erasure.
Posted by Andrew Koenig at 04:50 PM Permalink
|