Skip to main content
OverflowAI is here! AI power for your Stack Overflow for Teams knowledge community. Learn more
2 of 6
added 352 characters in body
Tony Tannous
  • 14.5k
  • 10
  • 55
  • 88

Branch-prediction gain!. It is important to understand, branch misprediction doesn't slow down programs. Cost of missed prediction is just as if branch prediction didn't exist and you waited for the evaluation of the expression to decide what code to run(further explanation in the next paragraph).

if (expression)
{
    // run 1
} else {
    // run 2
}


Whenever there's an if-else statement, the compiler generates assembly code, while the expression is evaluated to see if you should continue in the if block or to just jump to the else block. You actually gamble on one of them and start executing it. If the expression was good, then wonderful you gained the time it took to evaluate it, if not, the pipeline is flushed and you return to the statement prior to the evaluation of the else-if and the other block is run.

Visualization: Lets say you need to pick route 1 or route 2. Waiting for your partner to check the map, you have stopped at ## and waited, or you could just pick route1 and if you were lucky, then great you didn't have to wait, otherwise you will just turn back. While flushing pipelines is super fast nowaday taking this gamble is worthy. Predicting sorted data or a data that changes slowly is always easier and better than predicting fast changes.

 O       route1  /-------------------------------
/|\             /
 |  ---------##/    
/ \            \ 
                \
         route2  \--------------------------------
Tony Tannous
  • 14.5k
  • 10
  • 55
  • 88