PHP: is_null() vs. NULL ===

From the know your language department: If you can, go with the identical comparison operator ===. That’s a good approach in PHP for various reasons.

Only one example:

null === $var;

could be written as:

is_null($var);

but it is about more than 14 times slower according to some benchmarks onto those two expressions:

Iterations: 100000  (10 Runs)
 #  | NULL     | rel %  | is_null() | rel %  
----+----------+--------+-----------+--------
  1 |  0.02555 |  6.7 % |   0.37890 | 1482.9%
  2 |  0.02458 |  6.4 % |   0.38507 | 1566.6%
  3 |  0.02499 |  6.6 % |   0.37809 | 1512.8%
  4 |  0.02490 |  6.4 % |   0.38658 | 1552.6%
  5 |  0.02504 |  6.6 % |   0.38042 | 1519.2%
  6 |  0.02453 |  6.3 % |   0.38666 | 1576.0%
  7 |  0.02493 |  6.6 % |   0.37876 | 1519.5%
  8 |  0.02529 |  6.6 % |   0.38502 | 1522.5%
  9 |  0.02536 |  6.7 % |   0.37858 | 1492.6%
 10 |  0.02459 |  6.4 % |   0.38363 | 1560.4%

This is the benchmark script:

benchmark();
function benchmark() {
static $var;

$runs = 100000;
$rounds = 10;

header('Content-Type: text/plain;');
printf("Iterations: %d  (%d Runs)\n", $runs, $rounds);
printf(" #  | NULL     | rel %%  | is_null() | rel %%  \n");
printf("----+----------+--------+-----------+--------\n");

for($b=0; $b < $rounds; $b++) {

$start = microtime(true);
for ($i = 0; is_null($var), $i < $runs; $i++);
$timea = microtime(true) - $start;

$start = microtime(true);
for ($i = 0; null === $var, $i < $runs; $i++);
$timeb = microtime(true) - $start;

printf(" %2d |  %01.5f | %4.1f %% |   %01.5f | %6.1f%%\n", $b + 1, $timeb, ($timeb / $timea) * 100, $timea, ($timea / $timeb) * 100);

}

}

This entry was posted in PHP Development, Pressed, The Know Your Language Department and tagged , , , . Bookmark the permalink.

2 Responses to PHP: is_null() vs. NULL ===

  1. Stanley Kubrick says:

    Awesome… just the research I needed to prove what I thought to be true.

  2. Alexander Opitz says:

    There is also a difference between

    NULL === $var
    and
    $var === NULL

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s