Why is ===
faster than ==
in PHP?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
Faster should not just be measured in direct execution time (direct performance tests are almost negligible in this case). That said, I would need to see a test involving iteration, or recursion, to really see if there is a significant, cumulative difference (when used in a realistic context). The testing and debugging time you will save when dealing with edge cases should be meaningful to you, also
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
$a
and$b
were random integers [1, 100]And here are the results:
You can see that the speed is almost identical.
I don't really know if it's significantly faster, but === in most languages is a direct type comparison, while == will try to do type coercion if necessary/possible to gain a match.
Because
===
doesn't need to coerce the operands to be of the same type before comparing them.I doubt the difference in speed is very much though. Under normal circumstances you should use whichever operator makes more sense.
The == incurs a larger overhead of type conversion before comparison. === first checks the type, then proceeds without having to do any type conversion.
First, === checks to see if the two arguments are the same type - so the number 1 and the string '1' fails on the type check before any comparisons are actually carried out. On the other hand, == doesn't check the type first and goes ahead and converts both arguments to the same type and then does the comparison.
Therefore, === is quicker at checking a fail condition