4 ms·
There was a popular myth way back in the 90's that preincrement was always faster than postincrement because the former could generate a temporary. As if this
by ballard 13y ago
There was a popular myth way back in the 90's that preincrement was always faster than postincrement because the former could generate a temporary. As if this were the case:
/* x++ */
inline int postincrement(int *x) {
int temp = *x;
*x = *x + 1;
return temp;
}
/* ++x */
inline int preincrement(int *x) {
*x = *x + 1;
return *x;
}
But in typical usage, where the expression value is not used, it doesn't make any difference:
for (int i = 0; i < 10; ++i) {
If one looks at the assembly, it's clearly equivalent to:
for (int i = 0; i < 10; i++) {
Incidently, the latter seems more readable.
- ezy 13y agoI always thought this "myth" was confined to C++ code (iterators) where there may in fact be code that does something analogous to what your "postincrement()" does. Compilers are sometimes smart enough to remove the unnecessary operation in C++ (e.g. switch to ++x themselves), but I always use ++i for the same reason people simplify their usage of C in between sequence points --- it's an easy transformation, and why tempt fate?
- nly 13y agoThe compiler can't necessarily optimise i++ away in C++, because the ++operator or the destructor of the temporary iterator object returned may have side effects. It's still not quite equivalent to ballards postincrement() though, because the C++ standard allows for that temporary copy operation to be optimised away
- bookface 13y agoI was actually asked in an interview at Google in 2011 whether pre- or postincrement was faster in a snippet of code where the expression's value wasn't used. When I said that I was pretty confident that the compiler would produce the same assembly in both cases, the interviewer insisted that pre- was faster based on the same logic you mentioned. To her credit, she didn't penalize me for disagreeing with her and I still got the offer.
- nilkn 13y agoThis is one of those things I've had in my head for years, and as a result of this I habitually use pre-increment in code, even in other languages. I think I haven't actually believed the "myth" myself, though, for quite a while.