Friday 5 October 2007

Implicit comparisons in PHP

Tobias Schlitt recently wrote a blog entry about the speed of PHP comparisons. In it, he mentions that using the === operator to compare types as well as values is faster than using the == operator to compare values only. This is something that has been known for a while and we've made it part of our coding standard for MySource4.

Yes, the performance improvement you get is minor, but even the smallest changes add up for a site with hundreds of thousands of page views a day. Think about how many comparisons would be done during a single page load and you'll see that even small improvements like this one start to become significant.

Something else he mentions is that comparing return values of functions is faster than using an implicit comparison. So, for example, this code:

if (isset($foo) === true) { ... }
is slightly faster than this code:
if (isset($foo)) { ... }

I'm not sure that the tests performed are accurate, but we don't use implicit comparisons in MySource4 either. Not because of performance but because the code is easier to read. Again, this is part of our coding standard and is enforced by the Squiz standard in PHP_CodeSniffer.

If you would also like to incorporate these simple changes into your coding standard, PHP_CodeSniffer is a great tool to help you enforce them and show you where you need to make modifications to your code. You can either use the included Squiz standard or incorporate the specific sniff, Squiz/Sniffs/Operators/ComparisonOperatorUsageSniff, into your own custom standard.