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


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

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

, and not vice versa?


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 wiki :

Without branch prediction, the pipeline must wait until the conditional branch instruction is executed in order to make the next fetch. 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 intended branch is then loaded and partially executed. If it is then found that the prediction was incorrect, 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 the Intel Core i7 processor, the pipeline depth is 14 stages.

Therefore, this kind of optimization should not be used without a preliminary analysis of its necessity. 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