> From: Leon Rosenberg [mailto:[email protected]]
> Subject: OT if/else or not if/else
> I was wondering if using if/else is not actually slowing down your code.
> Lets say I have three possible conditions, A, B and C, which are exclusive.
> My native approach would be:
> if (A){...}
> if (B){...}
> if (C){...}
> now some people would 'optimize' it as
> if (A){ ...} else if (B) {....} else if (C) { ....}
> and I think in the world of single-cpu computers this optimization could
> work.
This doesn't really have anything to do with the number of CPUs, but rather
whether or not a single core can execute instructions in parallel
(vectorization or multiple execution ports).
> But what is now, given that compilers can optimize stuff like this and tell
> the processor to calculate all 3 branches simultaneously, which is not
> possible for ifelse.
These two sets of code are semantically different. Unless the compiler (not
the programmer) can prove that A, B, and C are mutually exclusive, the first
example requires checking all three. Also, unless the block of code executed
for a prior true condition can be proven to not affect a later predicate (e.g.,
cannot alias, no side effects), the compiler must issue the three statement
blocks in order. Depending on the memory ordering model in play for the
statements, the compiler may be able to issue speculative reads for each block
of code, but that's very, very language specific.
A modern CPU core can also speculatively execute instructions, and will likely
do so with either sequence (assuming typical memory ordering constraints).
> Which one would you choose?
Definitely the if ... else if ... sequence, or the corresponding switch
statement, if feasible. Give the compiler as much help as you can to figure
out the programming intent.
- Chuck
THIS COMMUNICATION MAY CONTAIN CONFIDENTIAL AND/OR OTHERWISE PROPRIETARY
MATERIAL and is thus for use only by the intended recipient. If you received
this in error, please contact the sender and delete the e-mail and its
attachments from all computers.
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]