Why is === faster than == in PHP?
Because the equality operator ==
coerces, or converts, the data type temporarily to see if it’s equal to the other operand, whereas ===
(the identity operator) doesn’t need to do any converting whatsoever and thus less work is done, which makes it faster.
===
does not perform typecasting, so 0 == '0'
evaluates to true
, but 0 === '0'
- to false
.
There are two things to consider:
If operand types are different then
==
and===
produce different results. In that case the speed of the operators does not matter; what matters is which one produces the desired result.If operand types are same then you can use either
==
or===
as both will produce same results. In that case the speed of both operators is almost identical. This is because no type conversion is performed by either operators.
I compared the speed of:
$a == $b
vs$a === $b
- where
$a
and$b
were random integers [1, 100] - the two variables were generated and compared one million times
- the tests were run 10 times
And here are the results:
$a == $b $a === $b--------- --------- 0.765770 0.762020 0.753041 0.825965 0.770631 0.783696 0.787824 0.781129 0.757506 0.796142 0.773537 0.796734 0.768171 0.767894 0.747850 0.777244 0.836462 0.826406 0.759361 0.773971--------- --------- 0.772015 0.789120
You can see that the speed is almost identical.