Most probable first

Posted by Tim Koschützki, on Apr 18, 2007 - in PHP & CakePHP » Performance, Optimization & Caching

What means the "Most probable first" principle?

When you are dealing with control structures in php, you have to ensure that you abide by the "Most Probable First" principle. That means, that whatever part of your control structure seems to be the one that is most likely to occur, should be the one after the if-statement. Here is a code example:

php
  1. $r = rand(1,3);
  2.  
  3. if($r < 3) {
  4.         $a = 1;
  5. } else {
  6.        $b = 2;
  7. }

The script generates a random number between 1 and 3. The control structure check whether the value is 1 or 2, respectively. It is more probably that the value is 1 or 2 than it is 3. So you should check for that first.

Why is this beneficial for the scripts performance?

PHP is not going to parse the opcode for the parts of control structures that return false. So the variable $b is actually never created in php's memory and thus will not use up your machine's memory.

This is not relevant to any performance gains in small applications. However, think of large application with a couple hundred variables and control structures. You should make it a habit to go by the "Most probable first" principle, so you use it all the time.