Stackify is now BMC. Read theBlog

PHP Performance Optimization Guide

By: jmendez
  |  March 17, 2023
PHP Performance Optimization Guide

 When developing a web application based on PHP, it’s not enough to just solve the problem and project requirements. Server resources like storage, memory, and number of CPUs contribute to the price of the hosting; that’s why developers should take into consideration these resources when developing web applications.  On top of all of these, the application must run smoothly. There are hundreds of ways to do some sort of PHP performance optimization in web applications and here are a few of them.

PHP version matters

The latest version of PHP is one of the fastest, if not the fastest version of PHP out there. According to some reviews, PHP version 7 is much faster than PHP5. PHP versions are fully supported for two years from initial release. Below are the supported versions of PHP.

PHP Versions

There will be compatibility issues when migrating between these two versions, but the advantages, especially with the performance gain, will outweigh the development cost and time for the modifications. If you are using the following versions below, I suggest you upgrade to a current version for better PHP performance.

Migrating PHP Versions
PHP Versions

Single and double quote usage matters

This may seem the last thing developers should care about, but there has been a lot of tests conducted to prove using single quotes, especially in larger loops and strings, is significantly faster than using double quotes. Double-quoted strings will look first for some variables in it before it displays the string itself; that’s why it’s slightly slower than printing strings in single quotes. When you think about PHP performance optimization, the usage of single quotes for strings matters.

function doubleQuotes($iterations) {
    $temp_str = "";
    $start_time = microtime(true);

    for ($x=0; $x<$iterations; $x++) {
        $temp_str .= "Hello World! ";
    }

    echo "Time for doubleQuotes(): " . (microtime(true)-$start_time) . "</br>";
}

function singleQuotes($iterations) {
    $temp_str = '';
    $start_time = microtime(true);

    for ($x=0; $x<$iterations; $x++) {
        $temp_str .= 'Hello World! ';
    }

    echo 'Time for singleQuotes(): ' . (microtime(true)-$start_time) . '</br>';
}

doubleQuotes(500000);
singleQuotes(500000);

Time for doubleQuotes(): 0.065473079681396
Time for singleQuotes(): 0.027308940887451

From this test, the string with single quotes runs more than twice as fast compared to the string test with double quotes. The difference in milliseconds might look negligible, but this performance gain would help PHP web applications that are being accessed by hundreds of users every minute. So only echo with double quotes if displaying the value of the variable is required; if not, then it’s much faster to echo strings with single quotes.

Effect of count function in loops

Loops are used mainly to traverse an array; but if the condition of the loop uses the count function to count the number of array elements, then there will be an overhead cost in using this function.

for ($x=0; $x<count($arr); $x++) { }

$count = count($arr);
for ($x=0; $x<$count; $x++) { }

The best way to traverse an array using loops is to store the number of elements in an array once, and then use that variable for the loop condition. Because if the count function is used in a for loop or loop, then every time the loop iterates, the program recounts the array which adds to the number of processes in each iteration. The only way that a developer should use the count inside a loop is if there’s array processing inside the loop.

Close or unset variables

When querying the database, a connection has to be made and one way to do that is to declare a connection variable. We all know that each variable used or declared uses memory, so it would be a good practice to close the connection after the query or all the queries are complete.

$conn = new mysqli($servername, $username, $password, $dbname);
//queries here
$conn->close();

$myfile = fopen("sample-file.txt", "r") or die("Unable to open file!");
//read the contents
fclose($myfile);

Similar to opening files, after reading or writing to the file, the variable that handles the connection must be closed. Closing connections will greatly save memory usage even though multiple people are accessing the same request of a web application.

Static methods or properties uses fewer resources

Static methods in classes, when being used, don’t need to have its class instantiated. Unlike public methods or properties that need to have its class instantiated before it can be accessed, static methods can be directly called. When there’s a class with only one method that is being called a lot from other classes, then this method must be declared as a static one. This will reduce the memory usage of the application because variable or class instantiation requires memory.

Optimize SQL queries

Joins will not only make the code shorter, but the PHP performance gain is significant. Beginners usually make a select query to the first table, and then make another select query based on the results of the first select query.

$query1 = mysql_query("SELECT id FROM users");
while ($row = mysql_fetch_assoc($query1)) {
    $query2 = mysql_query("SELECT * FROM user_info WHERE user_id = {$row['id']}");
}

Besides, an HTTP request that has multiple database queries is a no-no in web development. If related database tables cannot be queried using joins, then that database needs to be normalized.

Another way to do performance optimization with SQL queries is to add indexes to some columns. In this way, the retrieval of records using indexed columns will be faster. Even though indexes requires additional storage space compared to just regular columns, having a fast retrieval rate for records is a good user experience. Usually, the columns that need to be indexed are the columns that are used in JOIN, ORDER BY, GROUP BY, and WHERE clauses.

SELECT * FROM employees WHERE address LIKE '%Kansas City%'

Using wildcards in queries will definitely make filtering results a lot easier, but this kind of query is one of the main reasons why a web application slows down. Instead of using strings to store repetitive values like cities and countries, it would be better to just store these kinds of fields as integers and have another database table to store those integers with their respective string values. In this manner, the retrieval using these fields will now require an integer instead of a string.

SELECT id, first_name, last_name FROM employees

If possible, if you are not going to use all the columns of a database table, only specify which columns in the SELECT query you are going to use instead of SELECT *. The more columns the query returns, the more memory, and processing power it will consume.

Minify your CSS and JavaScript

Another way for PHP performance optimization is minifying JS and CSS code; this will make it unreadable by humans, but when we are talking about web applications that are in production, readability of code is not a priority. Also minifying your code reduces the size of a file, which improves load times. Browsers can quickly parse these files because comments and white spaces are omitted, thus reducing the process of ignoring it. When obfuscating code to make it not readable by humans, only obfuscate the code that needs to be secured because this process could potentially blow up the code.

Use a CDN to optimize PHP performance

Web applications usually use libraries like Bootstrap and jQuery, and the best way to load these files is through the content delivery network, like Cloudflare. To optimize the performance of your web application, leverage a content delivery network (CDN). Most of our images, CSS or JS files are static, so it is wise to maintain cached copies of the content at a server closer to where the users are. In this way, data travel a shorter distance and will execute faster, and this will reduce latency in your application. Web applications that need PHP performance improvements must consider using CDNs to download resources. CDNs allows users to download contents from a closer source, rather than loading it from where the entire application is hosted, and this will greatly affect the loading time of the application.

Web Application Traffic

Another thing to consider is the traffic and how fast your application can respond to the requests of your users. In web applications, common problems are traffic, the number of users accessing the system, and the capacity of your server to handle requests and responses to specific requests. Stackify Retrace can monitor the traffic flow of your application.

Retrace assures that your application is working perfectly to satisfy your needs. Retrace supports Microsoft Azure, Amazon AWS, and Google GCP to maximize the capability of cloud-based monitoring to ensure the quality of your application.

Summary

If you want to monitor the performance of your PHP applications, Retrace would be one of the starting tools for you. It can also keep track and trace every web request in your application. It also runs fast and is always ready for your applications. One parameter it records is the loading times of the elements of an application. This will give developers a chance to see which part of the application is underperforming and needs to be improved.

More information on PHP performance optimization

These articles provide additional information about PHP performance optimization that might be useful for your PHP applications.

Improve Your Code with Retrace APM

Stackify's APM tools are used by thousands of .NET, Java, PHP, Node.js, Python, & Ruby developers all over the world.
Explore Retrace's product features to learn more.

Learn More

Want to contribute to the Stackify blog?

If you would like to be a guest contributor to the Stackify blog please reach out to stackify@stackify.com