PHP program optimization

Source: Internet
Author: User
: This article mainly introduces PHP program optimization. if you are interested in the PHP Tutorial, you can refer to it. PHP program optimization

Php program optimization involves a lot of content. The following describes PHP code optimization, Session mechanism optimization, cache middleware, and PHP code cache system (mainly APC acceleration.

Optimize PHP code

We can optimize PHP code only after we have enough skills. After coding a program, we usually let some senior programmers Review the Code, evaluate the quality of the program, and find out the points to be optimized. this process is also called Code Review. Next we will introduce some common PHP programming skills and some optimization principles that may be involved in the Code Review process.

1. upgrade to the latest PHP version.

You must know that programming languages are constantly evolving. new languages usually contain language vulnerability fixes and performance optimizations. As a professional, we need to pay attention to the emergence of new versions on a regular basis. for PHP, we can get the required information from the official website http://php.net.

2. Reduce include and require

Although PHP has already made some optimizations to this problem, it may cause performance degradation in a large number of cases. This process can be mitigated by installing the APC accelerator component.

3. use local variables instead of global variables

The speed of local variables is the fastest, especially in some cyclic logic, we try to use local variables for calculation. As to why global variables are not used, on the one hand, it is because of the operational efficiency, and on the other hand, it is because global variables are not easy to manage in 2.

4. try to use static functions or methods

If possible, we should try to define the function or method as static, that is, add the static tag, which may increase the program execution speed by several times.

5. release unused variables or resources

Do not rely too much on the PHP memory recycle mechanism. some unused variables or resources in the program should be released in time. we can use the unset method or directly set it to null. In addition, pay special attention to other components-related resources, such as database connections.

6. replace double quotation marks with single quotes to include strings

In PHP, strings are usually enclosed by single quotes, because double quotation marks may generate extra escape characters or variable parsing logic. the execution efficiency of single quotes is higher than that of double quotation marks.

7. blocking errors with the @ symbol reduces the script running speed.

For ease of use, some programmers prefer @ to block error messages. However, this method can reduce the running speed of scripts and is not recommended.

8. do not over-use PHP OOP

In order to better manage code, today's large PHP programs tend to use object-oriented thinking (OOP) to build program frameworks, but because objects usually occupy memory, too many class libraries may also generate a large number of include and require operations, resulting in additional overhead. Therefore, we need to make rational use of OOP ideas based on the actual situation. This problem can also be solved using the APC acceleration component.

9. use abstract classes instead of interfaces

Using the interface (inteerface) in PHP is costly and should be avoided during programming. Similar logical encapsulation can be replaced by abstract class.

10. Regular expressions are expensive.

Although PHP's regular expressions are very powerful, we need to know that their execution costs are equally high. if possible, we should try to use PHP's character processing functions instead.

11. compress the data to be stored as much as possible

The storage of any data occupies space resources of the system. Therefore, data should be compressed as much as possible to save space resources of the system. For example, when saving the IP address, you can use the ip2long function to convert the IP address to integer data for storage, and then use the long2ip function to restore it. In addition, gzcompress and gzuncompress can be used for compression and decompression of some big data.

12. use more efficient statements

The efficiency of PHP programming statements can also be divided into different levels. next we will compare the important statements, and pay attention to them when writing code.

  • Switch... case in the branch statement is more efficient than if... elseif... else
  • In loop statements, foreach is the most efficient, for is the second, while is the lowest
  • In the overlay statement, ++ $ I (prefix) is faster than $ I ++ (suffix)

13. use more efficient functions

PHP function libraries are rich. different functions can be used for the same function. However, the running efficiency of different functions is also different. we need to pay attention to the usage. below we will compare some common functions.

  • Character print function echo is faster than print
  • The character replacement function strtr is the most efficient, followed by str_replace, and the prea_replace regular expression is the lowest.
  • The array query function array_key_exists is the fastest, inset is the second, and in_array is the lowest.
  • CUrl for obtaining remote network files has the highest efficiency, operability, and flexibility. fsockopen is followed by file_get_contents and fopen are the lowest.

Although, for some programs whose logic is not very complex, the effect of code optimization may not be very obvious each time, it is very important to develop good programming habits, this is also the difference between common programmers and senior programmers. Not all of the PHP programming skills listed above, and mastering these skills cannot be completed overnight. The so-called learning is nothing more than summing up and accumulating in the learning and hands-on process, in order to bring your programming capabilities to the next level.

PHP optimizes the Session mechanism

Simply put, a Session is like a global variable that each user has. it is used to save any information that the user needs to save on the server. In fact, the Session function can be set in the system configuration file php. ini. of course, we can also use the ini_set function (ini_get get configuration) to set it from the program.

Auto_start (session. auto_start: whether to enable the Session function automatically. because creating a Session consumes system resources, the session_start function is usually used only when Sesson is required. Second, the Session validity period depends on the system conditions. If it is too long, too much session data may cause load problems. if it is too short, performance problems may also occur due to too frequent session creation. The default validity period of the system is 1440 seconds, that is, 24 minutes. in actual projects, we usually set the validity period between 1 and 8 hours. In addition, you must note that the default storage method used by PHP Session is file storage. in ini, we can use session. the save_handle method is used to select the desired storage method, but the efficiency of using the file storage method is relatively low, which is not conducive to system architecture expansion. in actual projects, the Session callback interface is often set through the session_set_save_handler method, used to control Session logic. common storage media include databases and distributed cache servers.

PHP Session optimization ideas. First, each Session creation consumes resources. do not use the session_start method in the global configuration file. Second, make sure that the Session ID is included in each Session request. if the server cannot obtain the Session ID, a new Session ID will be created. In addition, when selecting a storage method, try to use a fast storage medium, such as the high-speed cache server Memcache (d) and Redis.

Use cache middleware

The emergence of cache middleware is to cache the queried information in the server memory to replace the database processing requirements for most queries, thus reducing the pressure on data. Currently, Memcache and Redis are commonly used cache middleware in the industry. (For more information about how to build and use the two environments, see network resources ). Based on the results used in the actual project, the cache middleware can greatly improve the query speed on the server. In addition, the Redis Cache can also be used as a writing queue, that is, the data is first written to the Redis Cache, and then transferred to the data.

Use APC acceleration

With the continuous development of network applications, logic code becomes more and more complex, and the resource consumption for introducing a large class library code in the framework is also relatively high. Therefore, when it comes online again. We also need some code-level caches to accelerate code execution.

APC (Alternative PHP Cache, PHP code Cache system) is a very good PHP code Cache solution that improves PHP execution efficiency by caching and optimizing PHP intermediate code (opcode.

Note:Free PHP code caching techniques similar to APC include eAccelerator and XCache (Installation and difference: http://blog.csdn.net/mossader/article/details/6343354)

Optimize Data transmission

1. optimized the json protocol.

In the general design principles of communication protocols, universality and directness are the most important. Selecting the JSON protocol as the foundation of the application protocol is an optimization of the system.

2. use gzip for compression

The process from the server to the client requires a complex network. Therefore, there are two main factors that affect network transmission: network quality and data size. For the HTTP protocol, gzip is one of the mainstream compression algorithms currently. most HTTP servers support this compression algorithm (for the gzip compression function modules configured by Apche and Nginx, please search for network resources on your own)

To be continued ......

Note: This article is excerpted from Chapter 9 of "best practices for Android and PHP Development": Server Optimization (with deletions)

The above introduces the PHP program optimization, including the content, hope to be helpful to friends who are interested in the PHP Tutorial.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.