Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Performance of !isset() vs === null

I'm aware of the benchmarks for isset() vs empty(), but I have code I need to execute only when the argument is null. This is in a function that executes many times so I'd like to optimize it.

I know that isset() is faster than empty(), but what about !isset() vs. === null? I know that the variable will exist, so I only need to test it against null.

I'm thinking of the possible penalty for the ! operator.

like image 872
Bob Ray Avatar asked Jul 02 '17 06:07

Bob Ray


People also ask

Does Isset check for NULL PHP?

The isset() function is an inbuilt function in PHP which checks whether a variable is set and is not NULL. This function also checks if a declared variable, array or array key has null value, if it does, isset() returns false, it returns true in all other possible cases.

Does Isset check for empty?

The isset() function is an inbuilt function in PHP that is used to determine if the variable is declared and its value is not equal to NULL. The empty() function is an inbuilt function in PHP that is used to check whether a variable is empty or not.

What can I use instead of isset?

The equivalent of isset($var) for a function return value is func() === null .


1 Answers

I felt lazy asking someone else to benchmark this, so I tried a million iterations.

The difference is trivial, so !isset() is a better option since === null would throw an error if the variable was ever undefined.

One Million iterations:

   !isset()  .1118
   === null  .1046

BTW, there is an (also trivial) penalty for the ! operator.

   isset()  .1118
   !isset() .1203
like image 131
Bob Ray Avatar answered Oct 17 '22 10:10

Bob Ray