Home > Backend Development > PHP Tutorial > PHP program optimization

PHP program optimization

WBOY
Release: 2016-08-08 09:28:39
Original
966 people have browsed it

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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template