The latest version of PHP is one of the fastest scripting language and programmers are enjoying using it. However, maintaining the optimal performance of the PHP along with fast code execution is also necessary. The best tool to improve PHP performance is not found among the ready-made programs. You need to know what is the problem of performance to pay attention and how to solve them. In this article, we have tried to collect all that is needed for successful work with PHP applications.
PHP Performance is one of the cornerstones of the site speed. PHP performance may not be as easily improved as the browser (client) aspects of the site speed, it requires special attention of web developers and system administrators.
What is a good performance?
It should be borne in mind that the performance and speed are not synonymous. Optimum performance balance between speed, error-free, and scalability. For example, when writing Web applications you have to choose between two priorities:
- Speed priority by writing a script that preloads all memory;
- Scalability priority with a script that loads data blocks.
When to optimize PHP Code?
Experienced programmers from time to time retain the tested code, thereby finishing the project cycle. But it is reasonable to do only with the good performance of PHP applications!
How to achieve a good performance PHP application? It is necessary to carry out tests during the development process. Otherwise, you’ll have to rewrite large blocks of code to cause the application to function properly.
Optimize PHP code should be started before the creation of PHP applications! It is necessary to immediately evaluate the condition of your hardware and software to determine the parameters of their performance. This information when the application coding will assess the risks and gain concrete compromises. And you must use the appropriate test data , or the application code would be futile.
Optimization Tips for PHP
Writing a good code is an important first step in creating a fast and stable PHP applications. Applying the outset the methods described below, you will save time when searching for errors.
1. Use a ready PHP function
Wherever possible, use ready-made PHP function. Avoid writing your own functions. To do this, take the time to study the functions of PHP. Then, the application code will be faster and more efficient.
2. Use JSON instead of XML
PHP function json_encode () and json_decode () just incredibly fast. Therefore, the use of JSON is preferable to the use of XML.
If you still have to deal with XML, better to use a regular expression pattern that manipulates the DOM.
3. Use caching techniques
Cache memory is particularly useful for reducing the amount of downloaded data.
Bytecode caching using APC or OPcache greatly saves the execution time of the compiled script.
4. Remove the excess computing
If the same value of the expression is used repeatedly, calculate it in advance and assign a variable. Then there will have to be calculated each time.
5. Use isset ()
Comparisons using pairs count () , strlen () and sizeof () , isset () . This is a quick and easy way to search for values greater than zero.
6. Disable unnecessary classes
If you do not plan to use the classes or methods repeatedly, they do not need. If you want to still use the class, you should use the derived class methods, because they are faster than the base class methods.
7. Turn off the debug messages
Error messages are only required at the time of coding. But after starting the final task, they become another process that slows down code execution. Disable the message.
8. Cover the connection to the database
Dropping variables and closing of connections to the database will save precious memory.
9. Restrict database access
Try to use a set of queries to the database. This reduces the number of calls to the database, the application will run faster.
10. Use the string functions Str
str_replace faster than preg_replace , but strtr four times faster than str_replace .
11. Use single quotes
Whenever possible, use single quotes, not double. Double quotes are checked by the compiler variables, which reduces performance.
12. Use the three equal sign
Since ” = = =” verify the value of only one type, it makes the comparison operator ” = = =” faster than the operator ” =” .
Bottlenecks of PHP
Sometimes, of course, that scenario is a favorable alteration. However, there are problems that reduce the performance of PHP, not related to the application code. Therefore, developers need to understand the subsystems of the server, to identify and eliminate bottlenecks. Listed below are the areas that should be checked when problems arise with the performance.
1. Network
One obvious source of bottlenecks – a network. May not be enough network resources to process the transmitted data volume.
2. Central Processing Unit
Transfer of simple HTML pages through the network does not exhaust the server’s CPU, whereas PHP-application overloads it. You can at least use the multiprocessor server to process PHP-code more efficiently.
3. Shared memory
The lack of shared memory reduces interprocessor communication, which leads to performance degradation. Therefore, having a multiprocessor server, do not forget to use the shared memory.
4. File System
The file system becomes fragmented over time. Therefore, use the RAM file cache, which will speed up the access to the disk, if the cache is large enough.
5. Process Management
Make sure that the server is not overloaded with unnecessary processes. Remove any unused network protocols, virus scanners, mail servers, and hardware drivers.
PHP execution in multi-threaded mode also improves the response time to requests (but not recommended, in general, for heavy systems, because it creates additional costs for context switching different cores).
6. Other servers
If the application depends on external servers, their bottlenecks will reduce performance. In such a situation, alas, there is little change. However, you can always come up with some changes on its side to mitigate this drop in performance.
More Performance Tips for PHP
1. Use a kernel extension of the Zend OPCache
Since PHP is interpreted in the executable code, the programmer has to re-compile the code even with a small change to his works. Unfortunately, this is almost the same recompiling code decreases performance. This explains why a compiler cache – OPCache – very helpful.
Zend OPCache – is an extension that keeps the compiled code in memory. This allows PHP to the next time you run the code to check the marking of time and file size to determine if the source file of the change. If such changes were not, it will run the stored code.
2. Identify the delay database
As mentioned above, performance problems are not always associated with the code. Most of the bottlenecks encountered in accessing application resources. Service access to PHP-application data can be up to 90 percent of the execution time. Therefore, it is first necessary to analyze all cases access to the database.
Make sure to log slow SQL queries included, to be able to identify them. Then study the slow queries, to evaluate their effectiveness. If you find that taking too many requests or the same questions are repeated unnecessarily, make the appropriate changes. Such changes should enhance application performance by reducing the time to access the database.
3. Clean the filesystem
Analyze file system inefficiencies, ie make sure that the file system is not used to store sessions. Most importantly – keep an eye on the statistics functions file: file_exists () , filesize () and filetime () . Getting these functions inside the loop leads to performance problems.
4. Carefully display and monitor API
Most Web applications that are dependent on external resources using remote the API. Though remote API is out of your control, you can mitigate the problem performance API. For example, it is possible to cache the API-conclusion or make background calls the API. Set reasonable intervals for API-requests, and, if possible, show the display API deduces without API response.
5. PHP profiling
OPcache use and management of external resources enough to most of the applications were carried out safely. But if your needs grow, it’s time to profile PHP. Of course, a complete profiling PHP-code, time-consuming, but it gives comprehensive information about the performance of PHP-applications. There are public programs for profiling PHP-code, such as Xdebug.
Monitoring
The web application can work well a minute, but sudden problems with traffic can interrupt normal operation. However, this can be prepared. It is clear that changes always take time, effort and money, and always difficult to say whether the cost of the investment. The best way to justify the decisions is by continuously collecting the data.
Software Control PHP performance immediately evaluate the effects of any changes you make. Of course, you need to know that it is appreciated. In this regard, the speed and memory usage – the best indicators of performance, as they affect the page load time, which is very critical for Web applications.
Despite the fact that data collection is important, you must turn off the control system when it is not needed because the log stream slows down the application. On the other hand, these logs provide valuable information on improving performance. Thus, it is necessary to periodically monitor the peak traffic periods.
Performance Improvement
PHP evolution continues. The latest change in the development of PHP 8 is the addition of the compilation “on the fly”, or JIT -kompilyatsii, which will create even faster web applications. As the pace of technological progress is growing, growing user expectations. Therefore, developers should always closely monitor the latest changes.
While Building a web app always remember that today’s applications can not work next year. You may have to make changes to ensure stable performance of PHP.