14 C and C++ Source-Level Optimizations Chapter 2
25112 Rev. 3.06 September 2005
Software Optimization Guide for AMD64 Processors
2.4 Expression Order in Compound Branch
Conditions
Optimization
In the most active areas of a program, order the expressions in compound branch conditions to take
advantage of short circuiting of compound conditional expressions.
Application
This optimization applies to:
• 32-bit software
• 64-bit software
Rationale
Branch conditions in C programs often consist of compound conditions consisting of multiple
boolean expressions joined by the logical AND (&&) and logical OR (||) operators. C compilers
guarantee short-circuit evaluation of these operators. In a compound logical OR expression, the first
operand to evaluate to true terminates the evaluation, and subsequent operands are not evaluated at all.
Similarly, in a logical AND expression, the first operand to evaluate to false terminates the evaluation.
Because of this short-circuit evaluation, it is not always possible to swap the operands of logical OR
and logical AND. This is especially true when the evaluation of one of the operands causes a side
effect. However, in most cases the order of operands in such expressions is irrelevant.
When used to control conditional branches, expressions involving logical OR and logical AND are
translated into a series of conditional branches. The ordering of the conditional branches is a function
of the ordering of the expressions in the compound condition and can have a significant impact on
performance. It is impossible to give an easy, closed-form formula on how to order the conditions.
Overall performance is a function of a variety of the following factors:
• Probability of a branch misprediction for each of the branches generated
• Additional latency incurred due to a branch misprediction
• Cost of evaluating the conditions controlling each of the branches generated
• Amount of parallelism that can be extracted in evaluating the branch conditions
• Data stream consumed by an application (mostly due to the dependence of misprediction
probabilities on the nature of the incoming data in data-dependent branches)
It is recommended to experiment with the ordering of expressions in compound branch conditions in
the most active areas of a program (so-called “hot spots,” where most of the execution time is spent).