Search code examples
phpperformanceshort-circuiting

php order of execution


Say, you have a condition like this;

if ($condition_1 && $condition_2)

and you have the option of writing it as

if ($condition_2 && $condition_1)

Now, if condition_1 takes 1 ms to figure it out whether it is true or false and condition_2 on the other hand takes a lot longer, say 1000ms!, which way would you write the above condition as? the slower one on the right or on the left?

I assume that when one of the conditions is found to be FALSE, PHP would not bother to check whether the other condition is TRUE. If it did, that would be the biggest surprise of the century!


Solution

  • C and C++ break on first FALSE in AND condition. This is also the case with PHP. So, I would suggest putting the shorter one first. This example clearly demonstrates the case:

    function short(){
        return false;
    }
    
    function long(){
        sleep(5);// sleep for 5 secondsd
        return true;
    }
    
    if ( short() && long() ){
        echo "condition passed";
    }else{
        echo "condition failed";
    }
    

    This will almost immediately print "condition failed" without waiting for 5 seconds....