PHP has a huge variety of built-in functions, but sometimes they aren't quite as efficient as you might imagine. This is nearly always intentional: the PHP developers strive for correctness first and performance second, which is of course what you want as your default standpoint. But if you do a little research, you'll find that sometimes you can take a short-circuit and see a major performance boost.
To give an example, consider how you might pull a random value out of an array. PHP has a built-in function for this called array_rand(), but it's actually quite slow because it doesn't know what kind of array it's dealing with â€“ are the keys numbers, are they strings, or are they something else entirely? So before it can pull out an array value, it first needs to pull together a list of all the keys to choose from.
In contrast, if you know your array has no keys other than the default index it comes with, you can simply generate a random number between 0 and the size of your array, and pull out the element at that index. The performance difference is massive, and only gets bigger as your arrays get larger.
It's also worth noting that performing any kind of function call has a performance hit compared to regular code, so if you're working in performance-critical code (nested loops, anyone?) you might consider writing your code in full rather than calling a function.
A curious example of function replacement is isset(), which can be used like array_key_exists() to see whether a key exists in an array. But it turns out that isset() is significantly faster because it's not a real function â€“Â it's a language construct that just happens to look like a function. So, the function call is avoided, and that part of your code runs 10x faster.
Eric Raymond, in his marvellous book "The Art of Unix Programming" (available online at this link but really worth buying), has a wonderful quote from Steve Johnson, an early Unix hacker responsible (amongst other things) for the Portable C Compiler and Yacc. The quote is this: "Dennis Ritchie encouraged modularity by telling all and sundry that function calls were really, really cheap in C. Everybody started writing small functions and modularizing. Years later we found out that function calls were still expensive on the PDP-11, and VAX code was often spending 50% of its time in the CALLS instruction. Dennis had lied to us! But it was too late; we were all hooked..."
Want to learn PHP 7?
Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!
If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!
Next chapter: Use the Zend Optimizer for older PHP versions >>
Previous chapter: Use your tools wisely
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.