Why is isset () more efficient for testing than "==="?

To summarize, I made a loop with several iterations to check the effectiveness of each test:

$iterations = 99999999; $var = null; 

Test Comparison

  if ( isset( $var ) ) { } 

'===' comparison

  if ( $var === null ) { } 

And I have this journal, in microseconds:

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

This is a little curious for me. Why is isset() faster than a single comparison operator like === ?

+7
php
source share
3 answers

Comparison === is a strict test, meaning that the two objects you are comparing must be of the same type. When you break it down in plain English, it's actually not so strange that === takes a little more time. Consider a parser for 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 must perform an additional check before it can determine if the variable matches the condition, so it’s not so strange that it is a bit slower.

+4
source share

Isset is not a function: it is an embedded language. Using isset is faster than using a function.

Another thing is that isset is used everywhere, so it makes sense that it was profiled to death, whereas === may not have received so much love.

In addition, you will need to dig a profiler into the PHP source to see exactly what is going on.

+1
source share

I am not sure what I would call 100 million "several iterations." It seems you have accumulated about half a second of the difference, divide it by 100 million, and you will get a colossal difference of 5 nanoseconds per iteration if my math is correct. The difference is so small that it can simply lead to the fact that isset has only one operand in this context, and === - two.

It is impossible to even discuss the implementation details of the Zend mechanism of the two examples without specifying a specific version of PHP; source code is a moving target. Even minute changes in implementations will affect the results for many omissions. I would not be surprised if you find that the opposite occurs in some versions of PHP and / or in another context.

isset itself is covered by three different op codes in the virtual machine, depending on the context:

Simple compiled variables like your example: ZEND_ISSET_ISEMPTY_VAR

Arrays: ZEND_ISSET_ISEMPTY_DIM_OBJ (requires 2 operands, var and index)

Object properties: ZEND_ISSET_ISEMPTY_PROP_OBJ (also 2 operands, profile name and name)

This is an interesting question for the sake of curiosity, but we are in the field of hair splitting, and this is probably not a real optimization strategy.

0
source share

All Articles