title: What is the effect of ordering if...else if statements by probability?
body: <p>Specifically, if I have a series of <code>if</code>...<code>else if</code> statements, and I somehow know beforehand the relative probability that each statement will evaluate to <code>true</code>, how much difference in execution time does it make to sort them in order of probability? For example, should I prefer this:</p>
  
  <pre><code>if (highly_likely)
    //do something
  else if (somewhat_likely)
    //do something
  else if (unlikely)
    //do something
  </code></pre>
  
  <p>to this?:</p>
  
  <pre><code>if (unlikely)
    //do something
  else if (somewhat_likely)
    //do something
  else if (highly_likely)
    //do something
  </code></pre>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>Important: this question assumes that the <code>if</code> 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.</p>