debuggable

 
Contact Us
 

Most probable first

Posted on 18/4/07 by Tim Koschützki

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:

$r = rand(1,3);

if($r < 3) {
        $a = 1;
} else {
       $b = 2;
}

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.

 

You can skip to the end and add a comment.

Mgccl said on Jun 08, 2007:

This usually have a really small impact on the code because at most, there is only a few more conditions to test.
Unless it's in a loop.

Tim Koschuetzki said on Jun 08, 2007:

That'S why I provided the last paragraph:

"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."

Of course you are right, but in a really big application, with loops, nested loops and the like it will make a difference. I was aiming at developing a sense of "most probable first" among my readers, as that is the better way to go for the longterm application.

Don't you agree?

Mgccl said on Jun 09, 2007:

xD.. sorry, I usually read articles in a way that I might miss some paragraphs.

Tim Koschuetzki said on Jun 09, 2007:

xD Not a problem. I should have highlighted it a bit more perhaps.

This post is too old. We do not allow comments here anymore in order to fight spam. If you have real feedback or questions for the post, please contact us.