What is the effect of ordering if…else if statements by probability?

后端 未结 10 1806
花落未央
花落未央 2020-12-07 13:39

Specifically, if I have a series of if...else if statements, and I somehow know beforehand the relative probability that each statement will evalua

10条回答
  •  心在旅途
    2020-12-07 13:53

    Also depends on your compiler and the platform you’re compiling for.

    In theory, the most likely condition should make the control jump as less as possible.

    Typically the most likely condition should be first:

    if (most_likely) {
         // most likely instructions
    } else …
    

    The most popular asm’s are based on conditional branches that jump when condition is true. That C code will be likely translated to such pseudo asm:

    jump to ELSE if not(most_likely)
    // most likely instructions
    jump to end
    ELSE:
    …
    

    This is because jumps make the cpu cancel the execution pipeline and stall because the program counter changed (for architectures that support pipelines which are really common). Then it’s about the compiler, which may or may not apply some sophisticated optimizations about having the statistically most probably condition to get the control make less jumps.

提交回复
热议问题