c++ – Does it make sense in a `switch` statement or` if .. else` statements to specify conditions in order of decreasing possibility of occurrence?

Question:

Does it make sense in a switch or statements like if (...) ... else if (...) ... else ... to specify conditions in the order of decreasing possibility of occurrence? That is, for example, if we know that there are more triples and twos than ones in the array, then do the following check:

if (x==3) ... else if (x==2) else ...

, and not vice versa?

Answer:

I will add that the processor has such a module as branch prediction , which allows you to optimize such instructions by predicting which branch will be executed. Quote from the wiki :

Without branch prediction, the pipeline must wait for the conditional branch instruction to execute in order to make the next fetch. The branch predictor avoids wasting time trying to figure out a branch. The branch is selected based on the previous results of the condition check. The proposed branch is then loaded and partially executed. If it is then found that the prediction was not performed correctly, the results of the incorrect branch are discarded and the correct branch is loaded into the pipeline, causing a delay. The amount of delay depends on the length of the conveyor. For an Intel Core i7 processor, the pipeline depth is 14 stages.

Therefore, this kind of optimization should not be used without first analyzing its need. Using gcc it is possible to add hints for the branch prediction module, for example (from the Linux kernel):

#define likely(x)       __builtin_expect((x),1)
#define unlikely(x)     __builtin_expect((x),0)

if (likely(condition)) {
   ...
}
Scroll to Top