PHP Program Optimization

Source: Internet
Author: User
Tags apc php language php session php programming php tutorial server memory
PHP Program Optimization

PHP Program Optimization is more content, the following focus on PHP code optimization, session mechanism optimization, the use of cache middleware and PHP code cache system (mainly APC acceleration) several parts.

Optimizing PHP Code

It is only after mastering enough skills that we can optimize the PHP code by line. When the program coding is done, we usually ask some more experienced programmers to review the code, evaluate the quality of the program, and identify the points that need to be optimized, called Code Review. Let's introduce some of the more common PHP programming techniques, as well as some of the optimization principles that may be involved in the Code Review process.

1. Upgrade to the latest PHP version

As you know, the programming language itself is evolving, and the new version of the language will typically contain the language's own bug fixes and performance optimizations. Therefore, as a professional, we need regular attention to the new version of the emergence, for PHP, we can get the information from the official website http://php.net/.

2. Reduce include and require

Although PHP itself has done some optimizations for this problem, it is possible to degrade performance in the case of heavy usage. This process can be mitigated by the method of installing the APC Accelerator component.

3. Use local variables instead of global variables

The speed of local variables is the fastest, especially in some loop logic, we use local variables as much as possible to perform operations. As for why global variables are not used, one is because of the efficiency of the operation, on the other hand, considering that global variables are not easy to manage in 2.

4. Use static functions or methods as much as possible

If possible, we should try to define the function or method as static, that is, add the static tag, which may cause the program to execute several times faster.

5. Releasing variables or resources that are not used

Do not rely too much on PHP memory recycling mechanism, some of the programs can not use variables or resources should be released in a timely manner, we may use the Unset method, or directly set it to null. In addition, you should pay special attention to other resources related to components, such as database connections.

6. Use single quotes instead of double quotes to contain strings

In PHP, strings are usually enclosed in single quotes, because the use of double quotes may produce additional logic for character escapes and even variable parsing, and single quotes are more efficient than double quotes.

7. Using the @ symbol mask error will slow down the script

For ease of use, some programmers prefer to use @ to mask error messages, but this can slow down the script and is deprecated.

8. Do not overuse PHP's OOP

To better manage the code, larger PHP programs are now more inclined to use object-oriented thinking (OOP) to build the framework of the program, but because objects tend to be more memory-intensive, there are too many class libraries that can generate a lot of include and require operations, resulting in additional overhead. Therefore, we should use the OOP idea rationally according to the actual situation. This problem can also be mitigated by using APC accelerator components.

9. Use abstract classes instead of interfaces

The cost of using the interface (Inteerface) in PHP is very high and is avoided as much as possible when programming. Similar logical encapsulation we can usually use abstract classes instead.

10. The use of regular expressions is costly

While the regular expression functionality of the PHP language is very powerful, we need to know that its execution costs are equally high and, where possible, to use PHP's character-handling functions instead.

11. Compress the data you need to store as much as possible

The storage of any data needs to occupy the space resources of the system, so the data should be compressed as far as possible, thus saving 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 to integer data for storage, and then restore through the LONG2IP function. In addition, some big data can also use gzcompress and gzuncompress to compress and decompress.

12. Use more efficient statements

The efficiency of the PHP programming statement is also high and low, the following we compare its more important statements, in the future you need to pay attention to writing code.

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

13. Use more efficient functions

PHP has a very rich library of functions, and the same functionality can be done using different functions. However, the efficiency of different functions is also different, we use is to pay attention to, below we have some common functions to compare.

    • Character print function echo faster than print
    • The character substitution function strtr The most efficient, str_replace second, prea_replace regular replacement is the lowest
    • Array query function array_key_exists fastest, inset second, In_array lowest
    • Get remote network files CURL efficiency and operability, maximum flexibility, fsockopen,file_get_contents and fopen minimum

Although, for some applications where logic is not very complex, it may not be obvious that every time the code is optimized, it is important to develop good programming habits, which is the difference between a normal programmer and a senior programmer. Not all of the PHP programming skills listed above, and to master these skills is not overnight can be completed, the so-called learning is boundless, only in the process of study and hands-on accumulation, in order to make their own programming ability to a higher level.

PHP optimization session mechanism

Simply put, the session is like a global variable for each user, to hold any information that the user needs to save on the server. In fact, the function of session sessions can be set in the system configuration file php.ini, of course, we can also use the Ini_set function (Ini_get get the configuration) from the program settings.

It is generally not recommended to enable Auto_start (Session.auto_start: auto-enable) because creating a session consumes system resources, and we usually only use session_ when we need to use Sesson. Start function to open the session function. Second, the duration of the session needs to be based on the situation of the system. If it is too long, it can cause too much session data to cause a load problem, and too short a join can be a performance issue due to too frequent session creation. The system default time is 1440 seconds, which is 24 minutes, in the actual project we will usually set this time between 1-8 hours. It is also important to note that the default storage method used by PHP Session is file storage, in php.ini we can select the desired storage mode by Session.save_handle line selection, but the use of file storage is less efficient and not conducive to system architecture expansion, In the actual project, the session callback interface is often set by the Session_set_save_handler method, which is used to control the logic of Session sessions, the common storage media is database, distributed cache server and so on.

The optimization idea of the PHP Session. First, the resource consumption is generated each time the session is created, and do not assume that the Session_Start method is used in the global configuration file. Second, each session request needs to be sure to bring the session ID, because the server does not get the session ID, and it will be recreated. In addition, when choosing storage mode, try to use fast storage media, such as cache server Memcache (d), Redis, etc.

Using Cache middleware

The advent of the cache middleware is to cache the information that is queried in the server memory, instead of the database processing most of the query requirements, thereby alleviating the pressure of the data. At present, the industry more commonly used cache middleware for Memcache and Redis (both the environment to build and use and differences, readers please find network resources, not detailed here). Depending on the effect used in the actual project, the cache middleware can often greatly improve the query speed of the server. In addition, the Redis cache can be used as a write queue, where data is written to the Redis cache before being dumped into the data.

Using APC acceleration

With the development of the network application, the logic code becomes more and more complex, and the resource consumption of the large class library code in the framework is higher, so it is on the line again. We also need to use some code-level caching to speed up code execution.

APC (Alternative PHP cache,php Code cache System) is a very good PHP code caching solution that improves PHP execution efficiency by caching and optimizing PHP intermediate codes (opcode).

Note: free PHP code caching technology at the same level as APC Eaccelerator and XCache (Installation and differences: http://blog.csdn.net/mossader/article/details/ 6343354)

Optimized data transfer

1. Optimizing JSON protocol

In the general design principles of communication protocols, universality and indirection are the most important. The choice of JSON protocol as the basis of Program application protocol is an optimization of the system.

2. Using gzip compression

Data from the service side to the client's process needs to pass through the complex network, therefore affects the network transmission The main factor has two, one network quality, second data itself size. For the HTTP protocol, Gzip is one of the current mainstream compression algorithms, most of the HTTP server support this compression algorithm (about Apche, Nginx configuration gzip compression function module, please find network resources yourself)

To be Continued ...

Note: This article is excerpted from "Best Practices for Android and PHP Development" chapter Nineth: Service-side optimization (censored)

The above describes the PHP program optimization, including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

  • 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.