The said:
Hi all,
Recently I was asked the question about whether ++U or U++ is
faster if U is a user defined type. What's the answer?
Thank you
According to the "Effective C++" and "More Effective C++"
books by Scott Meyers, the prefix form (++U) should be
preferred over the postfix version.
As far as speed is concerned, the difference is negligble
depending on how large the type is for U; or how complex
an increment operation is. One should alway profile
the _whole_ program before worrying about efficiency
of one expression or statement.
Profile your own code. If the section that _needs_
optimizing contains the increment operator, have the
compiler print out an assembly language listing of
that section. See how the compiler is translating
the increment. If _you_ can optimize that one statement
better in assembly, then reorganize the source to
provide hints to the compiler. I really doubt that
a person can optimize only the incrementing in assembly
due to the overhead involve in a call to an assembly
language function. A person may be able to optimize
better than the compiler by using inline assembly,
but by this time, you are wasting more time playing
with the compiler than producing code and finishing
the project.
Just pick a preference and stick to it. Worry about
the efficiency after the program works correctly
and is robust. If there is a _need_ for space or
time for optimization, then perform it at the end.
Sometimes, when the program is running extremely
slow or is extremely huge during development, some
optimizations may be necessary. For example, if
an embedded system runs out of execution space
before the integration phase is completed, optimizations
should be performed (such as removing unnecessary
code). But, in general, save optimizations for
after the progam is finished.
Spend your time on a more worthwhile endeavor,
such as making the code more readable.
--
Thomas Matthews
C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq:
http://www.parashift.com/c++-faq-lite
C Faq:
http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book