问题
Let's say I have a variable that will always be a string.
Now take the code below:
if($myVar === "teststring")
Note: $myVar
will always be a string, so my questions is
Which is quicker/best, using ===
(indentity) or the ==
(equality)?
回答1:
Testing for identity is always faster, because PHP does not have to Type Juggle to evaluate the comparison. However, I'd say the speed difference is in the realms of nanoseconds and totally neglectable.
Related reading:
- PHP type comparison tables
- Type Juggling
回答2:
===
will be slightly faster, but more importantly, It enforces that $myVar
will be a string so you don't have to worry about the possible effects of it being some other type.
回答3:
In general when I code, I use == over ===, however, using the identity is more precise, and also, slightly faster (difference is minimal).
The difference between the two is likely irrelevant for whatever you need.
来源:https://stackoverflow.com/questions/3053420/and-operators-in-php