Should one use `if ($a != NULL)` or `if ($a !== NULL)` to control program flow?

10.5k views Asked by At

This is perhaps a painfully basic question to answer, but I'm wondering about performance issues regarding using PHP's if identical !== versus if equal != to control flow.

Consider the following trivial PHP function:

<?php
 function test_json($json = NULL) {
  if ($json != NULL) {
   echo 'You passed some JSON.';
  } else {
   echo 'You failed to pass any JSON.';
  }
 }
?>

From a performance standpoint, is it preferable to employ if identical (!==) to prevent PHP iterating through variable types, attempting to find a valid comparison?

I assume that !== first compares the variable types, and if that fails, it immediately returns FALSE? I've used != since PHP3 almost as a reflex. Now that I'm working on some much more computationally-intensive projects, minute performance considerations become more of a concern.

Other comments on flow control optimization are, of course, welcome!

2

There are 2 answers

4
Michael Fenwick On BEST ANSWER

I haven't done any performance tests on loose vs strict comparison operators, but for what you are trying to do, I would instead recommend something like

if (!is_null($json)) {
    do_stuff()
}

More information on is_null() at http://www.php.net/manual/en/function.is-null.php

EDIT: a note in the comments of the php page I linked to above has some results showing that the === operator is slightly faster than the == operator, both of which are faster than is_null(). However, another note points out that "The execution time difference between ===NULL and is_null is less than 250 nanoseconds. Go optimize something that matters." I'd have to agree there. So all that said, I would suggest you go with what you deem to be the most readable.

0
miqbal On

You could write a test code like this before asking; according to test "Using "===" is 30x quicker than is_null()."

http://www.php.net/manual/en/language.types.null.php#77937