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 ===
( identity operator ) doesn't need to do any converting whatsoever and thus less work is done, making it faster.
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.
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
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.
===
does not perform typecasting, so 0 == '0'
evaluates to true
, but 0 === '0'
- to false
.
The == incurs a larger overhead of type conversion before comparison. === first checks the type, then proceeds without having to do any type conversion.
In conclusion === is faster because don't converts the data type to see if two variables have same value, but when you need to see if two variables have same value you will use == if doesen't mather what type are variables, or === if is important also the type of variables.