← Back to the Blog

PHP Performance - Why is it important

By Matthew Setter
PHP Performance - Why is it important

Performance is an area which many of us agree is important, but which, for many of us, perhaps doesn’t get the attention it should. Why? It’s like many things which sound technical; we love them, because they’re challenging, difficult, hard, and especially not for mere mortals.

We talk about them so that some of the lustre associated with them will rub off on us. Yet we avoid them because we doubt ourselves, or because we may suspect they’re beyond our level of skill or competence. It needn’t be this way. In this post, I’m going to show you four key ways in which you can both improve and measure the performance of your PHP applications, with not much effort, time, or skill required. Sound reasonable? Let’s begin.

Why It’s Important

Actually, before we begin, why is performance important? It’s important for two, key, reasons: cost and the environment. Whether you’re a bean counter or an environmentalist, performance is important. OK, there’s satisfaction in knowing your application’s not using any more resources than what it needs - sure - but that’s not the main reason to push for performance.

I’ve singled out these two reasons on purpose. For far too long, the stock standard solution, the “accepted practice” if you will, to software challenges was to throw more hardware at it. Sure, this might be OK in the immediate or short term, as it gets you out of a bind. But over the long term, the impact that this kind of thinking has is very expensive. What’s more, it encourages lazy programming practices.

Why justify continual cost outlays, when you can review your applications and have them do all that they need - with less? What’s more, you’ll be doing your bit for the environment, by not using more power and resources than needed. OK, the bragging rights of having the leanest application in the rack is still pretty good too. So let’s see how you can make your applications sing with PHP.

Upgrade to PHP 7 (or at least version 5.6)

The first thing you want to do, if you’re able, is upgrade to PHP 7. Admittedly right now you can’t; the alpha release was only made available recently; and the stable release isn’t due out till October this year. However it’s on the way.

But as it stands, according to Zend, version 7 is reputed to be from 25 - 70% faster than version 5.6 (the current stable release). That’s not enough for you? According to the phpng documentation, on which PHP 7 is based, you can expect speed improvements of up to 110%. That’s incredible!

If you want performance, you want this release.

In a normal course of affairs, you’d have to profile your application, identify bottlenecks, and apply some of the other strategies we’ll cover today. But with this change, you don’t have to do anything. All you need do is upgrade.

When a performance gain is so easy to achieve, I strongly encourage you to get out there now, download the alpha release, build it, test it, test your application running it, and report any bugs you find. That way, when the stable release becomes available - you’re ready! What’s handy to know is that Conetix is preparing to move to version 7, almost as soon as it’s stable. So if you’re hosting here, you’re in good hands.

Use an Op Cache

If you’re not familiar with an op cache, it dramatically improves the performance of a PHP script, or application, by pre-compiling the code in to bytecode the first time the script is parsed. Any subsequent times that the code is requested, if there’s bytecode already available, and the code hasn’t changed since the last request, then the cached bytecode is used. This avoids the time and processing power involved in parsing and compiling the script.

Similar to upgrading your version of PHP, implementing an op cache involves no code changes, yet can yield up to a 74% performance improvement. What makes it even better is that op caches have been around for a while with PHP, specifically APC and XCache. However, APC doesn’t support versions of PHP from 5.5 onwards. If you are on 5.5 or 5.6 though, you can use the newer OPCache instead.

How Do You Install It?

If you want to install APC, checkout the official instructions, as part of the PHP manual. If you’re on Ubuntu or Debian, the following should work for you:

bash sudo apt-get install php-apc 
sudo /etc/init.d/apache2 restart # or your webserver of choice

Alternatively, if you’re compiling from source, you can install it at this stage. If you want to work with OPCache, you don’t need to install anything, as it’s bundled with PHP 5.5. All you need to do is then enable and configure it as best suits your needs.

How Can You Measure Cache Usage?

Good question. But in both cases, it’s easy to do. If you’re using APC, there’s a script available with the downloaded source, called apc.php, which you can find in /usr/share/doc/php-apc/apc.php.gz. If you’re using OPCache, there are a number of options available, OCP - Opcache Control Panel and opcache-status by Rasmus Lerdorf.

Use a Caching Server

We’ve looked at the easiest options, now let’s start looking at some more difficult options, starting with caching servers. Caching servers, as the name implies, cache content, objects, and information for later use.

This can be anything from application objects, data retrieved from a remote data source, generated page content, and anything in-between. If you’ve not used one before, they’re extremely handy, and conceptually quite straight-forward. Let’s say your application makes a number of requests to a database, to retrieve the information required in your application. Each of these requests may involve a lot of overhead. For instance:

  • They require a connection to be made to the database
  • The SQL request has to be sent to the database
  • The data generated has to be retrieved
  • The connection needs to be closed

This doesn’t include the processing overhead required by the database server. Just by this superficial example, you get an idea that if you can avoid it, you should. To use a caching server, you first check if a cached copy of the data you need is available. If it is, you use the cached copy, if not, you make a request for the data, cache the data for next time, and continue processing as normal.

 What Options Are Available?

Like almost everything in PHP, there are several options available, from the simplest of Memcached, right up to more sophisticated servers, such as MongoDb, Cassandra, Hadoop, and Redis. Depending on your setup, these may be provided by your host, or you may have to set them up separately. Check with your host as to whether they support one or more of them or not. For each of these options, PHP has both native drivers, and contributed libraries.

A Working Example

Now let’s look at a basic example of using caching. In the code below, I’ve skipped over the initialisation of a connection to a caching server, the example doesn’t need that complexity. Then you see that we’ve initialised a cache key, called our-expensive-data-cache-key. This could be anything, from a few thousand rows database resultset or just a simple object.

// create connection to cache server 
// …

$cacheKey = ‘unique-cache-key’;
$result = $cache->getItem($key, $success);
if (!$success) {
$result = doExpensiveStuff();
$cache->setItem($key, $result);

Then, we call getItem() on our cache, which retrieves the data, if it’s available, using our cache key as an identifier. If not, we then do some expensive operation, and call setItem(), passing in our cache key, and the result of the operation, storing it in the cache for next time. If the data was available, we’d be able to skip the expensive operation and continue processing.

If you use a good cache library, in the code above, Zend\Cache, it will make interacting with any caching server, almost, this simple. Identify bottlenecks in your application and try caching the heavy operations.

Review Your Database Queries

Now let’s look at one last, but significant, way in which you can speed up the performance of your PHP applications - database query analysis. This is a pet peeve of mine quite honestly. Despite PHP being wedded to MySQL for so long, databases still seem to have the reputation of being a generic data dump.

Yet SQL is one of the most powerful tools in your technical arsenal, one which you’ll use repeatedly throughout your career. So you owe it to yourself to get a good handle on both how to do it properly, and secondly how to analyse and improve query performance.

Regardless of your database vendor, whether it’s MySQL, Oracle, MS SQLServer, PostgreSQL or something else, you’ll have a tool which provides a query, or query execution, plan for the SQL queries being run. If this is your first time hearing the term, a query plan tool analyses a SQL query, giving you a detailed breakdown of how it will work internally.

You’ll find out a range of information, including:

  • The number of tables considered
  • The query type
  • Whether indexes are used

You’ll also find out other advanced details about what the database server will do when running your query. From there, analogous to a step-through debugger, you’ll learn whether the query is doing what you think it will, and how taxing it will be on the database server. Assuming MySQL as a default for a moment, here’s a detailed explanation from them on what it does and what’s involved:

Depending on the details of your tables, columns, indexes, and the conditions in your WHERE clause, the MySQL optimizer considers many techniques to efficiently perform the lookups involved in an SQL query. A query on a huge table can be performed without reading all the rows; a join involving several tables can be performed without comparing every combination of rows. The set of operations that the optimizer chooses to perform the most efficient query is called the “query execution plan”, also known as the EXPLAIN plan. Your goals are to recognize the aspects of the EXPLAIN plan that indicate a query is optimized well, and to learn the SQL syntax and indexing techniques to improve the plan if you see some inefficient operations.

It’s quite an involved topic, one which my friend Shameer C, over at SitePoint, explains quite well. Definitely have a read through that post to see, first-hand, how to use the tool on your own queries.

Wrapping Up

And that’s four ways which you can use to immediately start improving the performance of your PHP applications. Some require no code changes, some do. Depending on the make up of your application, some will give you a much greater performance gain than others.

But a combination of all four, where possible, will definitely give you the best bang for your proverbial buck. I strongly encourage you to learn all you can about these four areas, as they’re definitely where you’ll get the most amount of return for your investment.