Performance, particularly on busy sites, can be critical - after all, if you can speed up your code by 10%, that decreases your hardware load by 10%, saving you the need to upgrade. There are a number of ways you can improve the performance of your scripts, and we will be covering as many as have space for. We will also be dispelling various myths about optimisation, and hopefully by the end of this chapter you will be confidently about to re-write fundamentally flawed algorithms, tune implementations of good algorithms, make your MySQL queries fly, and more.
Before we begin, I would like to make it quite clear that optimisation is the process of improving performance of your code, whether to use less space or run faster - it is usually a trade-off. Optimised code is not necessarily "perfect code", it is just better than unoptimised code.
Furthermore, there is rarely if ever such a thing as "too fast". In my spare time, I have been working on my own pet project: a gigantic online PHP strategy game. Actions occur at round end, which is triggered by a cron job every ten minutes. With a thousand dummy users in the system, round end takes over seven seconds, during which database writes are locked so that people cannot make changes. In the past I have spent hours and hours just to cut one part of that round end from 0.002 seconds to 0.001 seconds per player - it might not sound like a lot, but as far as I am concerned every single second counts. If you have tried out half of the recommendations here and find you have reduced the run-time for a script from four seconds down to one second, don't stop there - go for the fastest code you can get.