Specifically, if I have a series of if
…else if
statements, and I somehow know beforehand the relative probability that each statement will evaluate to true
, how much difference in execution time does it make to sort them in order of probability? For example, should I prefer this:
if (highly_likely)
//do something
else if (somewhat_likely)
//do something
else if (unlikely)
//do something
to this?:
if (unlikely)
//do something
else if (somewhat_likely)
//do something
else if (highly_likely)
//do something
It seems obvious that the sorted version would be faster, however for readability or the existence of side-effects, we might want to order them non-optimally. It’s also hard to tell how well the CPU will do with branch prediction until you actually run the code.
So, in the course of experimenting with this, I ended up answering my own question for a specific case, however I’d like to hear other opinions/insights as well.
Important: this question assumes that the if
statements can be arbitrarily reordered without having any other effects on the behavior of the program. In my answer, the three conditional tests are mutually exclusive and produce no side effects. Certainly, if the statements must be evaluated in a certain order to achieve some desired behavior, then the issue of efficiency is moot.