Benchmarking and optimising PHP web applications

With all Turing complete programming languages, there are many different ways of performing the same task.

Be it sorting, searching, looping through a list, outputting content to the screen or to a file – they can all be accomplished by a variety of differnet methods. PHP is no different, therefore it is worth looking at the different ways in which tasks can be performed, and benchmarking their performance. This allows us, as developers, to identify places in which simple changes can heavily optimise code and increase the speed at which it runs, while decreasing the load it puts on the system its running at.

Taking a look at The PHP Benchmark, we can see that, in PHP, even calculating the length of a loop in advance can offer a ~ 50x improvement in speed.

Optimising PHP - loops in PHP

Another interesting PHP benchmark is comparing the various ways in which an associative array can be looped through. As it should be, it seems the convenient ‘foreach’ structure (built primarily for this purpose) offers the best performance. Interestingly though and perhaps unexpectedly, defining the key and the value variables in your foreach loop definition offers 2.5 x performance when compared to just providing a variable for just the value.

Optimising PHP foreach read loops

Optimising of code, in any language, must be carefully considered. There is always a hidden balance between getting the most speed out of your code and making it readable and maintainable in the future. A great example would be language frameworks, which offer fantastic programmatic features and built-in patterns for developers at the cost of an increased overall code base. In most quality frameworks, the benefits of improved code structure that come from its use far outweigh the performance costs and overhead of loading and using the framework’s functionality.

Similarly, a web application could theoretically be written in pure x86 assembly code. However, no one typically does this. It would be incredibly difficult to manage and would require a very specific skill set which is significantly more prevalent in computer science fields outside of web application development. Instead, web developers typically use a server-side language such as PHP, Rails or ASP.Net, often combined with a programming framework that abstracts concepts such as database access, follows one or more specific code design patterns, and allows for easier separation of presentation and business logic code.