G
Guest
Hi,
why n++ executes faster than n+1..... or does it realli execute faster?
thanks
Venugopal.B
why n++ executes faster than n+1..... or does it realli execute faster?
thanks
Venugopal.B
VenuGopal said:why n++ executes faster than n+1..... or does it realli execute faster?
I have heard interview questions about why would ++n executes faster
than n++?
The prefix operator will always be faster than the postfix.
The postfix
version involves a copy and internal call to the prefix. For simple
types the relative cost between the two should be small.
For more
complicated objects (e.g. iterating over a vector) the cost may be
larger.
The general consensus in C++ literature (More Exceptional C++,
More Effective C++) is that the prefix version should always be
preferred. Doing this you cannot go wrong. In addition, writing ++
instead of ++ costs nothing.
I think they would need a new CTO
No, (with standard side-effect perception) the postfix can never be
faster than the prefix. There is a difference.
None. look at the optimized code.
No, std::vector:const_)iterator is usually implemented by classes that
compiles and optimizes down to pointers. Look at the optimized code.
If you "optimize" your programs by writing "++x" instead of "x++" you
are doing something wrong. ++x and x++ have different semantics and you
should choose the one that fits, not the one you think is fastest.
Should you feel tempted to replace the statement "x = x + 1;" with
something else, you should use "++x;" since you don't care about the
side-effect of "x++", which *may* cost you something.
Even *if* you call the x++ operator, and it's implemented using copying
chances are the optimizer will still be able to remove that copying
because the returned object is unused.
In C# there are other reasons to think before using x++, for example x++
on C# defined class'es compiles but still gives you ++x, even if you
only implemented ++x!