Re:A glimpse of undefined behavior in C
by ballard on Saturday November 30, 2013 @06:12PM
(#6825105)
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:
But in typical usage, where the expression value is not used, it doesn't make any difference:
If one looks at the assembly, it's clearly equivalent to:
Incidently, the latter seems more readable.
[ Parent
| on HN ]
I 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?
The 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
Re:A glimpse of undefined behavior in C
by bookface on Saturday November 30, 2013 @07:00PM
(#6825313)
I 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.
This 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.