Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isset() is more efficient to test than '==='?

Tags:

php

Summarized, I made a loop with a few iterations to check the efficiency of each test:

$iterations = 99999999;
$var = null;

isset comparasion

  if ( isset( $var ) )
  {

  }

'===' comparasion

  if ( $var === null )
  {

  }

And i have this log, in microseconds:

'isset()': 1.4792940616608
'===': 1.9428749084473

For me, this is a little curious. Why isset() function is faster than one comparison operator as ===?

like image 685
Alexandre Thebaldi Avatar asked Aug 13 '15 05:08

Alexandre Thebaldi


2 Answers

The === comparison is a strict check, meaning that the two objects you're comparing have to be of the same type. When you break it down in plain English, it's actually not that weird that === needs some more time. Consider the parser to do this:

if (isset($var)) {
    // Do I have something called $var stored in memory?
    // Why yes, I do.. good, return true!
}

if ($var === null) {
    // Do I have something called $var stored in memory?
    // Why yes, I do.. good! But is it a NULL type?
    // Yes, it is! Good, return true!
}

As you can see, the === operator needs to do an additional check before it can determine if the variable matches the condition, so it's not that strange that it is a little bit slower.

like image 81
Oldskool Avatar answered Sep 28 '22 12:09

Oldskool


Isset is not a function: it is a language built-in. Using isset is faster than using a function.

The other thing is that isset is used all over the place, so it makes sense that it's been profiled to death, whereas === maybe hasn't received as much love.

Other than that, you'd have to dig in the PHP source with a profiler to see exactly what's going on.

like image 37
zneak Avatar answered Sep 28 '22 12:09

zneak