PHP Performance of !isset() vs === null
Asked Answered
P

1

8

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.

Preparation answered 2/7, 2017 at 6:11 Comment(0)
P
13

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
Preparation answered 2/7, 2017 at 6:21 Comment(2)
yes === null is faster but will throw an error if the value was not set. But if you set the variable to null at the start of your script (so you are sure that the variable will either have a value or null) you can use the comparison operator, which is faster. But the difference is really that small, it's better to opt for readability in your code here.Galosh
Although I did not benchmark this, theoretically speaking, isset() also has an additional benefit in readability when doing multiple checks for required variables - isset($a, $b, $c) returns true only if all variables are set and would return false as soon as any not-set variable is encountered, checking from left to right. In other words: isset() can replace multiple similar !== null checks with one prioritised parameter list which is definitely better for readability.Fredericfrederica

© 2022 - 2024 — McMap. All rights reserved.