PHP program optimization
PHP program optimization
There are many contents in PHP program optimization. The following focuses on PHP code optimization, Session mechanism optimization, use of caching middleware and PHP code caching system (mainly APC acceleration).
and we have mastered enough mastered all the skills have been mastered to master enough skills, we can optimize the PHP code, we can optimize the PHP code. After the program coding work is completed, we usually ask some more senior programmers to review the code, evaluate the quality of the program and identify points that need optimization. This process is also called Code Review. Below we will introduce some common PHP programming techniques, as well as some optimization principles that may be involved in the Code Review process.
1. Upgrade to the latest PHP version
You must know that the programming language itself is constantly evolving, and new versions of the language usually include bug fixes and performance optimizations in the language itself. Therefore, as professionals, we need to pay attention to the emergence of new versions regularly. For PHP, we can obtain the required information from the official website http://php.net/.
2. Reduce include and require
Although PHP itself has made certain optimizations for this problem, it may cause performance degradation under heavy use. This process can be alleviated by installing the APC accelerator component.
3. Use local variables instead of global variables
Local variables are the fastest, especially in some loop logic, we use local variables to perform operations as much as possible. As for why global variables are not used, on the one hand it is because of operating efficiency issues, and on the other hand it is because global variables are not easy to manage. 静 4. Try to use static functions or methods. If we may try to define functions or methods as static, that is, add static tags, which may increase the speed of program execution several times.
5. Release unused variables or resources Don’t rely too much on PHP’s memory recycling mechanism. Some unused variables or resources in the program should be released in time. We can use the unset method, or directly remove them. Set to null. In addition, you should pay special attention if you encounter other resources related to components, such as database connections. 6. Use single quotes instead of double quotes to include strings In PHP, strings are usually included in single quotes, because using double quotes may cause additional character escaping or even variable parsing logic. Single quotes The execution efficiency is higher than that of double quotes. 7. Using the @ symbol to shield errors will reduce the running speed of the script For the convenience of use, some programmers like to use @ to shield error messages, but this approach will slow down the running speed of the script and is not recommended. 8. Don’t overuse PHP’s OOP In order to better manage the code, larger PHP programs now tend to use object-oriented thinking (OOP) to build the program framework, but because objects usually take up more memory , too many class libraries may produce a large number of include and require operations, resulting in additional overhead. Therefore, we must use OOP ideas reasonably according to the actual situation. This problem can also be alleviated using APC acceleration components. 9. Use abstract classes instead of interfaces The cost of using interfaces in PHP is very high, so try to avoid using them when programming. We can usually use abstract classes instead for similar logic encapsulation. 10. Using regular expressions is expensive Although the regular expression function of the PHP language is very powerful, we need to know that its execution cost is also high. Where possible, PHP's character processing should be used as much as possible function instead. 11. Compress the data that needs to be stored as much as possible The storage of any data requires space resources of the system, so the data should be compressed as much as possible to save the space resources of the system. For example, when we save an IP address, we can use the ip2long function to convert the IP address into integer data for storage, and then restore it through the long2ip function. In addition, you can also use gzcompress and gzuncompress to compress and decompress some big data. 12. Use more efficient statements The efficiency of PHP programming statements also varies. Below we compare the more important statements. You need to pay attention to it when writing code in the future.- The efficiency of switch...case in the branch statement is higher than if...elseif...else
- The efficiency of foreach in the loop statement is the highest, followed by for, while is the lowest
- In the overlay statement ++$i( Prefix) is faster than $i++ (suffix)
13. Use more efficient functions
PHP has a very rich function library, and the same function can be completed using different functions. However, the operating efficiency of different functions is also different. We need to pay attention to it when using it. Below we compare some commonly used functions.
- Character printing function echo is faster than print
- Character replacement function strtr is the most efficient, str_replace Secondly, prea_replace is the lowest regular replacement
- array query function array_key_exists is the fastest, inset Secondly, in_array is the lowest
- Get remote network file cUrl efficiency and Operability and flexibility are the highest, followed by fsockopen, file_get_contents and fopen are the lowest
Although, for some programs whose logic is not very complex, the effect of each code optimization may not be very obvious, but It is very important to develop good programming habits, which is also the difference between ordinary programmers and advanced programmers. The above list is not all of the PHP programming skills, and mastering these skills cannot be completed overnight; the so-called learning has no limit, and only by constantly summarizing and accumulating in the process of learning and hands-on, can one's programming ability be improved to the next level. Floors.
PHP Optimized Session Mechanism
Simply put, Session is like a global variable that comes with each user, used to save any information that the user needs to save on the server. In fact, the functions of the Session session can be set in the system configuration file php.ini. Of course, we can also use the ini_set function (ini_get to obtain the configuration) to set it programmatically.
It is generally not recommended to enable auto_start (session.auto_start: whether to automatically enable it), because creating a Session requires consuming system resources. We usually only use the session_start function to enable the Session function when we need to use Session. Secondly, the validity period of Session needs to be determined according to the system conditions. If it is too long, it may cause load problems due to too much session data; if it is too short, it may also cause performance problems due to too frequent session creation. The system's default valid time is 1440 seconds, which is 24 minutes. In actual projects, we usually set this time between 1-8 hours. Also note that PHP The default storage method used by Session is file storage. In php.ini, we can select the required storage method through session.save_handle selection line. However, using file storage method is relatively inefficient and is not conducive to system architecture expansion. In actual projects, The session callback interface is often set through the session_set_save_handler method to control the logic of the session. Common storage media include databases, distributed cache servers, etc.
PHP Session optimization ideas. First of all, resource consumption will occur every time a Session is created. Do not use the session_start method in the global configuration file for granted. Secondly, you need to make sure to bring the Session ID with each session request, because if the server cannot obtain the Session ID, it will create a new one. In addition, when choosing a storage method, try to use fast storage media, such as cache servers Memcache(d), Redis, etc.
Use caching middleware
The emergence of caching middleware is to cache the queried information in the server memory to replace the database to handle most of the query requirements, thereby reducing the data load. pressure. Currently, the more commonly used caching middleware in the industry are Memcache and Redis (for the environment construction, usage, and differences between the two, readers please search for network resources, and I will not introduce them in detail here). Depending on the effect used in actual projects, caching middleware can usually greatly improve the query speed of the server. In addition, the Redis cache can also be used as a write queue, that is, the data is first written into the Redis cache and then transferred to the data.
Use APC to accelerate
With the continuous development of network applications, logic code has become more and more complex, and the resource consumption of introducing huge class library code into the framework is also relatively high. So when you go online again. We also need to use some code-level caching to speed up code execution.
APC (Alternative PHP Cache, PHP code caching system) is a very good PHP code caching solution. It improves PHP execution efficiency by caching and optimizing PHP intermediate code (opcode).
Note: Free PHP code caching technologies at the same level as APC include eAccelerator and XCache (installation and differences: http://blog.csdn.net/mossader/article/details/6343354)
Optimize data transmission
Among the general design principles of communication protocols, versatility and indirection are the most important. Choosing the JSON protocol as the basis of the program application protocol is itself an optimization of the system.
2. Use gzip compression
The process of data from server to client needs to pass through a complex network, so there are two main factors that affect network transmission, one is network quality, the other 2. The size of the data itself. For the HTTP protocol, gzip is one of the current mainstream compression algorithms. Most HTTP servers support this compression algorithm (for information on configuring the gzip compression function module for Apche and Nginx, please find network resources by yourself)
To be continued...
Note: This article Excerpted from Chapter 9: Server Side of "Best Practices for Android and PHP Development" Optimized (with deletions)
The above has introduced PHP program optimization, including various aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

To work on file upload we are going to use the form helper. Here, is an example for file upload.

In this chapter, we are going to learn the following topics related to routing ?

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Validator can be created by adding the following two lines in the controller.
