Home > Article > Backend Development > How to optimize PHP performance
When developing PHP-based web applications, it is not enough to just solve the problem and project requirements. Server resources such as storage, memory, and CPU count contribute to the price of hosting; this is why developers should consider these resources when developing web applications. Beyond that, the application must run smoothly. There are hundreds of ways to perform some kind of performance optimization in web applications. Here is a summary of some methods for PHP performance optimization.
1. PHP version is very important
PHP version 7 is much faster than PHP5. The PHP version is fully supported for two years from the initial release. Below are the supported PHP versions.
There will be compatibility issues when migrating between the two versions, but the benefits, especially the performance improvements, will outweigh the development costs and modification time. If you are using the following versions below, I recommend that you upgrade to the current version of PHP for better performance.
2. The use of single and double quotes is important
This seems to be the last thing that developers should pay attention to, But a lot of testing has been done to prove that using single quotes, especially in larger loops and strings, is much faster than using double quotes. A double-quoted string will first look up some of its variables before displaying the string itself; that's why it's slightly slower than printing a string with single quotes. The use of single quotes for strings is important when you think about performance optimization of your PHP project.
function doubleQuotes($iterations) { doubleQuotes($iterations) { $temp_str = "";= ""; $start_time = microtime(true);= microtime(true); for ($x=0; $x<$iterations; $x++) {for ($x=0; $x<$iterations; $x++) { $temp_str .= "Hello World! ";.= "Hello World! "; }} echo "Time for doubleQuotes(): " . (microtime(true)-$start_time) . "</br>";"Time for doubleQuotes(): " . (microtime(true)-$start_time) . "</br>"; }} function singleQuotes($iterations) {function singleQuotes($iterations) { $temp_str = '';= ''; $start_time = microtime(true);= microtime(true); for ($x=0; $x<$iterations; $x++) {for ($x=0; $x<$iterations; $x++) { $temp_str .= 'Hello World! ';.= 'Hello World! '; }} echo 'Time for singleQuotes(): ' . (microtime(true)-$start_time) . '</br>';'Time for singleQuotes(): ' . (microtime(true)-$start_time) . '</br>'; }} doubleQuotes(500000);(500000); singleQuotes(500000);(500000); Time for doubleQuotes(): 0.065473079681396Time for doubleQuotes(): 0.065473079681396 Time for singleQuotes(): 0.027308940887451Time for singleQuotes(): 0.027308940887451
Starting with this test, strings with single quotes run more than twice as fast compared to string tests with double quotes. The difference in milliseconds may seem negligible, but this performance gain will help web applications accessed by hundreds of users per minute. So if you need to display the value of a variable, just echo it with double quotes; if not, it's much faster to echo the string with single quotes.
3, The impact of the counting function in the loop
The loop is mainly used to traverse the array; but if the condition of the loop uses the count function to calculate the array number of elements, then using this function will incur overhead.
for ($x=0; $x<count($arr); $x++) { } ($x=0; $x<count($arr); $x++) { } $count = count($arr);= count($arr); for ($x=0; $x<$count; $x++) { }for ($x=0; $x<$count; $x++) { }
The best way to iterate over an array using a loop is to store the number of elements in the 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 will recalculate the array, which increases the number of processes in each iteration. The only way developers should use count in a loop is with array manipulation inside the loop.
4, Close or unset variables
When querying the database, a connection must be established. One way is to declare the connection variable. We all know that every variable used or declared uses memory so it is a good practice to close the connection after the query or all queries are completed. ,
$conn = new mysqli($servername, $username, $password, $dbname);= new mysqli($servername, $username, $password, $dbname); //查询//查询 $conn->close();->close(); $myfile = fopen("sample-file.txt", "r") or die("Unable to open file!");= fopen("sample-file.txt", "r") or die("Unable to open file!"); //读取内容//读取内容 fclose($myfile);($myfile);
Similar to opening a file, after reading or writing the file, the variables that handle the connection must be closed. Even if multiple people access the same request of the web application, closing the connection will significantly save memory usage.
5. Static methods or attributes use fewer resources
Static methods in a class do not need to instantiate its class when used. Unlike a public method or property, which needs to be instantiated before accessing it, static methods can be called directly. When a class with only one method is called a lot from other classes, this method must be declared as static. This will reduce your application's memory usage since memory is required for variable or class instantiation.
6. Optimize SQL queries
Connections will not only make the code shorter, but also improve performance. Beginners usually do a select query on the first table and then do another select query based on the results of the first select query.
$query1 = mysql_query("SELECT id FROM users");= mysql_query("SELECT id FROM users"); while ($row = mysql_fetch_assoc($query1)) {while ($row = mysql_fetch_assoc($query1)) { $query2 = mysql_query("SELECT * FROM user_info WHERE user_id = {$row['id']}");= mysql_query("SELECT * FROM user_info WHERE user_id = {$row['id']}"); }}
Additionally, HTTP requests with multiple database queries are taboo in web development. If you cannot use a join to query related database tables, the database needs to be normalized.
Another way to optimize performance with SQL queries is to add indexes to certain columns. This way, retrieving records using the index column will be faster. Although indexes require additional storage compared to regular columns, having fast retrieval rates for records is a good user experience. Typically, the columns that need to be indexed are the columns used in JOIN, ORDER BY, GROUP BY, and WHERE clauses.
SELECT * FROM employees WHERE address LIKE '%Kansas City%'* FROM employees WHERE address LIKE '%Kansas City%'
Using wildcards in queries certainly makes it easier to filter results, but such queries are one of the main reasons why web applications slow down. Instead of using strings to store repeated values like city and country, store these types of fields as integers and use another database table to store these integers and their respective string values. In this way, retrievals using these fields will now require integers instead of strings.
SELECT id, first_name, last_name FROM employees, first_name, last_name FROM employees
如果可能,如果您不打算使用数据库表的所有列,则只指定要使用的SELECT查询中的哪些列而不是SELECT *。查询返回的列越多,内存和处理能力就越大。
7、缩小CSS和JavaScript
性能优化的另一种方法是缩小JS和CSS代码; 这将使人们无法阅读,但当我们谈论生产中的Web应用程序时,代码的可读性不是优先事项。同时缩小代码会减小文件的大小,从而缩短加载时间。浏览器可以快速解析这些文件,因为省略了注释和空格,从而减少了忽略它的过程。当混淆代码使其无法被人阅读时,只需对需要保护的代码进行模糊处理,因为此过程可能会破坏代码。
8、使用CDN优化性能
Web应用程序通常使用Bootstrap和jQuery等库,加载这些文件的最佳方式是通过内容交付网络,如Cloudflare。要优化Web应用程序的性能,请利用内容交付网络(CDN)。我们的大多数图像,CSS或JS文件都是静态的,因此在靠近用户所在位置的服务器上维护内容的缓存副本是明智的。通过这种方式,数据传播的距离更短,执行速度更快,这将减少应用程序的延迟。需要性能改进的Web应用程序必须考虑使用CDN来下载资源。CDN允许用户从更近的源下载内容,而不是从托管整个应用程序的位置加载内容,这将极大地影响应用程序的加载时间。
9、Web应用程序流量
另一件需要考虑的事情是流量以及应用程序响应用户请求的速度。在Web应用程序中,常见问题是流量,访问系统的用户数量以及服务器处理特定请求的请求和响应的能力。比如Stackify Retrace可以监控应用程序的流量。
Retrace确保您的应用程序完美地满足您的需求。Retrace支持Microsoft Azure,Amazon AWS和Google GCP,以最大限度地提高基于云的监控功能,从而确保应用程序的质量。
The above is the detailed content of How to optimize PHP performance. For more information, please follow other related articles on the PHP Chinese website!