Version A :
if ((A)&&(B)) doSth;
if (B) doSthElse;
Version B :
if (B)
{
if (A) doSth;
doSthElse;
}
Which of these two is preferable, performance-wise?
Notes :
-
The actual code will be used some millions of times per second, so performance and speed is crucial. Before proceeding to profiling, could you please give me some input in case I’m missing something?
-
The code is being compiled using Clang++ on Mac OS X 10.6.8, using
-O3.
Assume A and B are both simple boolean values,
We need take into account the likelihood of what the condition resolves into:
short-cut evaluation: if (A) is likely to resolves to false than (B), write (A && B), otherwise (B && A).
branch predictability: use conditions that more predictable enclose big blocks. for example, if B is predictable, then 2nd form is preferred.
try to translate non-predictable conditional assignment into (? :), for example, prefer
to
if c is not predictable.
In this case, you want to substitute a control flow dependency by a data dependency, which can be compiled into a conditional move. It is net gain when the control dependency is not predictable.