PHP Includes and Optomization

Is the php compiler smart enough to not waste time including a large file since that code will never be reached? This is easiest to express through a simple example.



$asdf = true;

if ( $asdf )
    echo "hi!"
else
{
    include "lib/a_really_huge_file_with_lots_of_functions_and_code.php";
    echo "hi again!";
}


Would this take longer to run if $asdf was false?

I remember reading somewhere that PHP does “lazy” (I think that was term used) testing in conditionals. eg.

if( ($a < $b) && ($c < $d) && ($e < $f) )

when the first FALSE is encountered, PHP stops there, it doesn’t evaluate any following conditions.

I’m guessing it’s the same with if - else i.e. at the first TRUE the parser continues on, skipping what’s in the else.

EDIT: I was just thinking, though I can’t see myself doing it (I prefer readable code), but something like

if ( $loggedin && $results = $mysqli->query($query) )

could “work”.

It’s called short circuit evaluation.

well actually lazy is pretty awesome itself :slight_smile:

Thanks for the correction. That sure is a lot better sounding than “lazy” :lol:

You’ve already written the code, why not just execute it and find out?

Include warns you when the file doesn’t exist, you could have just run your original code with a bad path to see!

…Yeah a timed approach was more scientific; maybe run a few thousand iterations of each to make sure? :stuck_out_tongue:

This is so easy to test, I’ll leave the rest as an exercise to the reader!

Just kidding…


$time_start = microtime(true);

$asdf = false;

if ( $asdf )
{
    echo "yes!";
    usleep(1000000);
}
else
{
    include "../lib/lib_main.php";
    echo "noo!";
    usleep(1000000);
}

$time_end = microtime(true);
$time = $time_end - $time_start;

echo "Page loaded in $time seconds\
";

The results?


yes!Page loaded in 1.00009512901 seconds 
noo!Page loaded in 1.00189614296 seconds 

So yes. It appears as if the PHP compiler is smart enough to ignore unused code, and that bad programming practices can significantly add to execution time.

Hopefully somebody finds it useful. I know I did.

Did you try? And how big would an include have to be to cause a noticeable delay?