Thursday, June 2, 2022

Discover How to Diagnose and Fix Performance Problems in PHP Applications

The PHP development team has been hard at work, releasing new features and improvements to the PHP language, the web server in which it runs, and the databases that it connects to each and every month. The result of this activity by the PHP development team means one thing: performance problems in PHP applications are becoming more and more common! But don’t panic! With this guide on how to diagnose and fix performance problems in PHP applications, you’ll have all of the information you need to tackle these issues head-on.


Understand what happens under the hood

Many performance problems can be diagnosed just by using a tool like Xdebug or Chrome's developer tools. With both of these, you'll be able to see what's happening under-the-hood without having to deploy your app first. 

You might not realize that it takes five queries on average to display a single piece of content on your page or that an AJAX call blocks all other page loading while it happens. 

Seeing how these things affect your code will give you insight into what kinds of changes will help make things better; you might even find that some problems aren't fixable right away. But at least now you'll know what's happening and where you need to improve things.



Check your code for common mistakes

Before you start optimizing your code, it’s important to make sure there aren’t mistakes already present. Make sure your code is: clear, easy-to-read, properly indented, uses short variable names (four characters or less), avoids magic numbers, avoids excessive logic (e.g., branching/looping), uses comments appropriately—especially when APIs are used—and is free of typos and obvious syntax errors. If you aren’t sure whether something is a mistake or not, don’t be afraid to use Google.


Poor security practices

As a web developer, it’s your job to ensure that data isn’t compromised. In particular, you need to make sure that sensitive information is encrypted before it reaches users, but also that stored user credentials (such as passwords) are stored safely. 

It’s not just about keeping things safe from hackers — you also have an obligation to protect your own systems from malicious users who might want to steal from or damage your application or company. 

We suggest always using salted password hashes (and two-factor authentication whenever possible). For more information on best practices for storing passwords securely with PHP, check out Anthony Ferrara's post on a similar topic.

 

Making database queries twice

Many programmers struggle with performance optimization because they make redundant database queries. Sometimes it’s a matter of laziness, but other times it’s a matter of poor organizational skills. Either way, before you can speed up your application, you have to be able to diagnose where things are going wrong. 

This diagnostic involves adding some code that logs what queries are being executed (SELECT, UPDATE, INSERT) by your application when you log into it. 

You should then look at your log files for patterns that indicate unnecessarily repeated queries or an otherwise inefficient query pattern. Once you’ve done that: Keep all tables small: Large tables can really hurt an application's performance.


Misconfiguring the web server

Developers can use tools, such as Linux top or iftop, to find out how much memory an application uses. If a site has a heavy load, it is useful for developers to check how much of that load is caused by external requests. 

Developers can use iftop on Linux machines or Navicat/Kashoo on Windows servers (or whatever tool they normally use) to check how many resources are being used per hour. It's important for them to check what percentage of requests come from bots versus actual human users. In some cases, robots might be responsible for more than 90% of traffic.


Use a profiler

If you’re trying to figure out how well your application performs, there are a few tools that can help you out. If you’re using a hosted solution like Heroku or Amazon Web Services, your host will have many different options for analyzing application performance. 

If you’re running locally, there are lots of options available to aid your performance analysis: Linux has profile; Mac has Instruments; Windows has Visual Studio Profiler. 

Each tool gives you insight into which sections of code are taking up processing time—even if it means going down several levels deep into your web stack. From there, you can examine what needs improving and make sure those changes get made ASAP.


Determine the potential causes of bottlenecks

When it comes to performance issues, you can't assume that one thing is causing everything. If your site's running slowly, start by looking at both front-end and back-end performance; we'll get into those details a bit later on. 

Once you've pinpointed a potential bottleneck, ask yourself these questions: * Why could that particular process be causing slowdowns? * What can I do about it? * What do I know so far? * Where should I go next?


Follow the F.I.R.S.T (Files, Inodes, Resources, Sockets, Threads) rule

Performance issues can be caused by a huge number of things, which is why you need to know how to check for every possible cause. F.I.R.S.T stands for: Files, Inodes, Resources, Sockets, and Threads. 

Every time you experience a performance issue, run through these steps before you even start thinking about potential solutions. The order of each step is important – resolve any problems with file access before moving on to resources, then sockets, etc.

Benchmark it with XHProf

If you don’t have access to production data, performance profiling can be a real challenge. Luckily, if you’re running Apache, there’s a great open-source tool called XHProf that helps you collect performance data from your codebase. The process is relatively straightforward: create an xhprof.php file at your root directory (this will contain all of your profiling code), configure mod_xhprof for Apache, restart Apache and begin your profiling process by invoking php /path/to/your/root/.xhprof.php. Once configured correctly, XHProf should be able to capture diagnostic information at runtime and report back some performance statistics on functions in addition to function calls themselves.


 Use Unix tools such as top, lsof, free, vmstat etc.

A lot of performance information is available on most operating systems. For example, Unix/Linux provides tools like free, vmstat, top (and others) which will tell you about CPU and memory usage. The top tool is especially useful for investigating a long-running process: just type 'top' and watch how it updates every few seconds with new details. Running 'ps aux sort -nrk 2 -g' will let you see what's happening on your system at any given time. I recommend learning these commands so that you can learn more about your system when something breaks!


Use in-built functions like memory get usage

Knowing exactly how much memory your application is using is critical for effective performance management. The easiest way to find out is by checking built-in functions like memory get usage. This function will give you a snapshot of how much memory your application has allocated at any given time, allowing you to get an overall picture of whether your app is over-allocating or under-allocating resources. 

If your app seems well within acceptable memory limits, look into adding caching layers, offloading jobs that don't need to be done synchronously (like updating records while users are on a different page), and checking server configuration settings that might be causing undesired effects.

 

wrapping up

There are many different steps involved with finding, diagnosing, and fixing performance problems in your application. When you’re running into performance problems with one of your applications, be sure to walk through these steps carefully. As an added bonus, consider pairing up with a developer who has experience optimizing PHP apps - they can lend you an extra set of eyes that might catch something you’re missing. It also never hurts to make use of developer tools like New Relic that provide important insights that are hard to get by just looking at a terminal session or application log files. With a little work upfront, you can prevent even small performance issues from turning into big ones down the road.