Tell the losers to get a better compiler. The C and C++
if statement translates to very few machine instructions.
The Intel optimizing compiler is one of the best for x86 hardware... Make sure that you don't preload your
if statements with extra stuff they don't need, turn on the appropriate optimization level at compilation, and you'll get perfect code every time.
There is a difference, particularly with older compilers, that the ternary operator will produce better code when
assigning a value based upon a test. For example, something inspired straight off the Wikipedia (
http://en.wikipedia.org/wiki/Conditional_operator ):
*opening_time = is_weekend( day ) ? 1200 : 930;
This can potentially compile more efficiently than the equivalent:
1 2 3 4
|
if (is_weekend( day ))
*opening_time = 1200;
else
*opening_time = 930;
|
A really good compiler should catch that the two are identical, but not necessarily so. If it doesn't, then the code to dereference the target could be duplicated for each branch, whereas it would not be duplicated when using the
?:
operator -- producing a "more optimized"
if.
Here's the rub: the exact code generated by the compiler has nothing to do with your ability to write efficient, succinct, readable C or C++. The same code will compile and work properly, and usually
optimally, everywhere a C or C++ compiler is available. Some CPUs can do X more efficiently than others. Writing code that assumes optimization of a specific processor is ugly, hard to read and maintain, and makes it unportable or exceedingly inefficient on other processors.
Whereas, clean, well-written code compiles everywhere and gives the compiler the ability to do its job: generate optimal machine code. Engineers who want to second-guess the compiler and play assembler themselves are a detriment to the company -- they are wasting time playing with stuff that makes no difference.
In
specific instances it is worthwhile to code to a specific CPU and/or architecture. This is where assembly programming becomes useful. But outside specific needs like that it is an abuse of your employer's time to quibble about a 'more optimized if statement'.
Hope this helps.