Friday, April 18, 2008

=== null is faster than is_null

I hate using more than one method to do the same thing in my code: it makes it read inconsistently in my opinion. I try to keep it uniform so there are no surprises.

Lately I've been struggling to decide which of the following is the 'best' way to check if a given variable is null or not in PHP:

is_null($v)

$v === null
So I figured I'd try a rough and ready script to benchmark the two. The following will do:

$c = 1000000; // Iterations
$v = null; // Value to use in comparison
$d = null; // Dummy variable for assignment
$i = 0; // Counter
$s = microtime(true);

for ($i = 0; $i < $c; ++$i)
{
$d = is_null($v);
}

$s2 = microtime(true);

echo $s2 - $s . "\n";

for ($i = 0; $i < $c; ++$i)
{
$d = $v === null;
}

echo microtime(true) - $s2 . "\n";
?>
A million iterations of each should be sufficient. Everything is initialised before the loops so neither has an unfair advantage. I also tried running the script with $v set to numerous other types and values with no effect on the result, and finally tried swapping the loops around to ensure that running order was not a factor.

The result? Well, on my machine === null turns out to be roughly four times faster than is_null.

I find this quite surprising: === is a generic operator while is_null is a very specific function. The only cause I can think of is that the function call adds overhead.

So, there you go. If you need to check if a variable is null or not, === NULL is the faster way to go.

No comments: