PHP code optimization

Source: Internet
Author: User
Tags autoload apc check email validity connection pooling memcached php script zend zend server

1 Code optimization

1 Try to be static

If a method can be static, it is declared static, the speed can be increased by 1/4, even when I test, this improved by nearly three times Times.

of course, This test method needs to be executed at level 100,000 and above, the effect is Obvious.

In fact, the efficiency of static and non-static methods are mainly different in memory: static method to generate memory at the beginning of the program, instance method (non-static METHOD) in the program to generate memory in the run, so the static method can be called directly, the instance method to genetic the instance before the call, static speed, but more will occupy Memory.

Any language is the operation of memory and disk, as to whether object-oriented, only the software layer of the problem, the bottom is the same, but the implementation method is Different. Static memory is continuous, because it is generated at the beginning of the program, and the instance method applies discrete space, so of course there is no static method Fast.

A static method always calls the same piece of memory, and its disadvantage is that it cannot be destroyed automatically, and instantiation can be destroyed.

2 echo efficiency is higher than print

Because echo there is no return value, print an integral type is Returned. Test:

Echo0-0s (average 0seconds)print0-0seconds (average 0seconds)     

The difference is about 8%, on the whole echo is relatively fast.

Note: echo When you output a large string, it can seriously affect performance if you do not have an adjustment. Turning on Apache for mod_deflate compression, or opening ob_start the content into a buffer can improve performance Issues.

3 cycle Maximum number of times

Sets the maximum number of cycles before the loop, rather than in the Loop.

4 destroying variables in time

Arrays and objects are particularly memory in php, which is caused by the Zend engine in Php. In general, the memory utilization of the PHP array is only 1/10, that is, a C language inside the 100M memory array, in PHP 1G is necessary.

In particular, in the system of PHP as a background server, there are often problems with memory costs too Much.

5 Avoid using magic methods like __get, __set, __autoload, etc.

(for Reference only, open for Discussion)

Functions that begin with __ are named Magic functions that are triggered under certain conditions. All in all, there are several magic functions __construct () , __destruct () , __get () , __set () , Code class= "hljs bash" >__unset () , __call () , Code class= "hljs" >__callstatic () , __sleep () , __wakeup () , __tostring () , __set_state () , __clone () , __autoload () .

In fact, if the __autoload() class name is not efficient and the actual disk file (note, here refers to the actual disk file, not just the file Name) corresponds, the system will have to do a large number of files whether there is a judgment (need to be in each include path to find), It is well known that disk I/O operations are inefficient in determining the existence of a file, so this is autoload why the efficiency of the mechanism is Reduced.

therefore, When designing a system, we need to define a clear set of mechanisms for mapping the class name to the actual disk File. The simpler and clearer the rule, the higher autoload the efficiency of the MECHANISM.

Conclusion: the autoload mechanism is not a natural inefficient, only misuse autoload , the design of a bad automatic loading function will lead to the reduction of its efficiency.

So it is debatable to avoid using magic methods as much as possible __autoload .

6 requiere_once () and include_once () Compare resource consumption

This is because requiere_once() and include_once() need to determine whether the file has been referenced, so you can not use as much as Possible. Common require / include method to Avoid. In his blog, brother Bird has repeatedly declared as far as possible not to use require_once and include_once .

7 using absolute paths in include and require

If you include a relative path, PHP will traverse it to include_path find the File.
This type of problem is avoided with absolute paths, so less time is required to resolve the operating system path.

8 using $_server[' requset_time ']

If you need to get script execution time, it's $_SERVER[‘REQUSET_TIME‘] better than that time() .

As you can imagine, one is ready to use directly, and one needs the result of the Function.

9 replacing regular expressions with built-in functions

If you can use PHP internal string manipulation functions, use them as much as possible, instead of regular expressions, because they are more efficient than regular.

Not to say, the most consumption of performance.

Is there a useful function you missed? For example: strpbrk (), strncasecmp (), strpos (), strrpos (), stripos (), strripos ().

The STRTR () function is used to convert a specified character, if it is necessary to convert all of a single character, using a string instead of an array:

"efgh");        Array (//  bad

Efficiency improvement: 10 times Times.

10 using STRTR as a character replacement

str_replaceCharacter substitution singular is preg_replace quick to replace, strtr but str_replace 1/4 faster.

In addition, do not make unnecessary substitutions, even if there is no substitution, it str_replace will also allocate memory for its parameters. Very slow!

Workaround: use strpos Find first (very fast), see if you need to replace, if necessary, then Replace.

Efficiency: If replacement is needed, efficiency is almost equal and the difference is 0.1% around. If you do not need to replace: use strpos fast 200% .

11 using strings instead of arrays as arguments

If a function can accept both an array and a simple character as a parameter, try to use a character as a parameter. For example, the character substitution function, the argument list is not too long, you can consider an additional write a replacement code, so that each pass argument is a character, rather than accept the array as the find and replace Parameters. punches, 1+1>2 .

12 best not to use @

@masking errors can slow down the script and have a lot of extra work in the Background. @3 times times the efficiency gap. In particular, do not use in the cycle @ , in the 5 cycles of testing, even if the first use to error_reporting(0) turn off errors, after the completion of the cycle to open, faster than the use @ .

13 array Element quotes

$row[‘id‘]$row[id]7 times times faster than the speed, it is recommended to form the array key name quotation marks Habit.

14 Don't use the function in the Loop.

For example:

For ($x < count ($x + +) {} 

This method calls the function at each loop, count() and the efficiency is greatly reduced, suggesting this:

$len = count ($array);  for ($x + +) {}  

Let the function get the loop number once outside the Loop.

creating local variables in the 16 method

Creating local variables in a class method is the fastest, almost as fast as calling local variables in a method.

17 Local variables are twice times faster than global variables

Because the local variables are in the stack, when a function occupies a stack space is not very large, this part of the memory is likely to hit the cache, this time the CPU access efficiency is very high.
conversely, If a function uses both a global variable and a local variable, the CPU cache needs to switch back and forth when the two addresses are large, and then the efficiency drops.

18 Local variables instead of object properties

Creating an object property (a variable within a class, such as: $this->prop++ ) is 3 times times slower than a local variable.

19 Declaring a local variable in advance

Creating an undeclared local variable is 9-10 times slower than an already defined local Variable.

20 Caution declaring global variables

Declaring a global variable that is not used by any one function also degrades performance (as well as declaring the same number of local variables). PHP might check to see if the global variable Exists.

there is no relationship between the performance of Class 21 and the number of methods

After you add 10 or more methods to a tested class, performance is no Different.

22 in subclasses the performance of the method is better than in the base class23 functions faster than class methods

A function that calls only one parameter, and the function body is empty, takes a time equal to 7-8 $localvar++ operations, while the same Function's class method is approximately 15 $localvar++ operations.

24 using single quotes instead of double quotes is faster

Because PHP searches for a variable in a string surrounded by double quotes, the single quotation mark does Not.

The PHP engine allows the use of single and double quotes to encapsulate string variables, but their speed is very different! A string that uses double quotes tells the PHP engine to first read the string contents, find the variable in it, and change the value to the Variable. Generally speaking, strings are not variable, so using double quotes can cause poor performance. It is best to use a string connection instead of a double-quoted string.

"this is a plain string";  ' This is  a plain string ';  "mixed";                     ' This is a '. $type. ' string ';   
echo strings use commas instead of point connectors faster

echoMultiple strings separated by commas can be passed in as "function" arguments, so the speed is Faster. (description: echo is a language structure, not a real function, so the function is added double quotation marks). For example:

echo $str 1, $str 2;       //fast echo $str 1. $str 2;      //speed slightly slower  
26 try to be static

Apache/nginx Parsing a PHP script is 2 to 10 times times slower than parsing a static HTML page, so try to make the page static or use a static HTML Page.

28 Using caching

Either memchached or Redis Can.

High-performance distributed Memory Object cache system, improve the performance of dynamic network applications, reduce the burden of the Database.

It is also useful for caching code (op Code) so that the script does not have to recompile for each Request.

29 saving IP with integral type

Use the ip2long() and long2ip() function to convert the IP address into an integer, then store it in the database, and save the Non-character Type.

This reduces storage space by almost 1/4. At the same time, the address can be easily sorted and quickly find;

30 Check Email validity

Use CHECKDNSRR () to confirm the validity of the email address through the existence of the domain name, this built-in function can guarantee that each domain name corresponds to an IP address.

31 using mysqli or PDO

mysql_*Functions are not recommended, we recommend using enhanced mysqli_* series functions or using PDO directly.

32 try to enjoy using the ternary operator (?:)33 Whether components are required

Before you want to completely redo your project, see if there are ready-made components (on Packagist) available, installed through Composer. Components are the wheels that others have built, and they are a huge repository of resources that many PHP developers know.

35 masking sensitive information

Use the error_reporting () function to prevent potentially sensitive information from being displayed to the User.

The ideal error report should be completely disabled in the php.ini file. however, If you are using a shared virtual host, php.ini you can not modify, then You'd better add error_reporting () function, put in the first line of each script file (or with require_once () to Load) This effectively protects sensitive SQL queries and paths from being displayed when errors occur;

36 compressing a large string

Use gzcompress () and gzuncompress () to compress/unzip the large-capacity string, and then save the database In/out. This built-in function uses the GZIP algorithm to compress the string 90%.

37 Reference Pass parameters

A function has multiple return values through a parameter address reference, and a "&" in front of the parameter variable means that it is passed by address, not by Value.

38 fully understand the dangers of magic referencing and SQL Injection.

Fully understand "magic quotes" and the dangers of SQL Injection. I ' m hoping that most developers reading this is already familiar with SQL Injection. however, I list it here because it's absolutely critical to Understand. If you've never heard the term before, spend the entire rest of the day Googling and reading.

39 Some places use isset instead of strlen

When you manipulate a string and need to verify that its length satisfies a certain requirement, you will of course use the strlen () Function. This function executes quite quickly because it does not do any calculations and only returns the zval length of the known string stored in the structure (the built-in data structure of c, used to store PHP variables). however, because strlen() it is a function, it is somewhat slower, because function calls go through a number of steps, such as lowercase letters (words: lowercase, PHP does not differentiate between function names), and hash lookups, which follow the called Functions. In some cases, you can use the Isset () technique to speed up execution of your Code.

For example:

5) {    "Foo is too short";} //use isset ()if (!  Isset ($foo {echo "foo is too short";}      
40 use + + $i increment

When $i the increment or decrement of a variable is executed, $i++ it is ++$i slower. This difference is unique to PHP and does not apply to other languages, so please do not modify your C or Java code and expect them to become fast and useless. ++$ifaster because it requires only 3 instructions (opcodes), $i++ 4 instructions are Required. The post increment actually produces a temporary variable, which is then Incremented. The predecessor increment is incremented directly on the original Value. This is one of the most optimized processing, as Zend's PHP optimizer did. It is a good idea to keep this optimization in mind, as not all of the instruction optimizer will do the same optimizations, and there are a large number of Internet service providers (ISPs) and servers that do not have the command optimizer Installed.

40 do not randomly copy variables

Sometimes in order to make the PHP code more neat, some novice php (including Me) will copy the predefined variables into a shorter name of the variable, in fact, the result is an increase in memory consumption, will only make the program more slowly. imagine, in the following example, if the user maliciously inserted 512KB bytes of text into the text input box, which will result in 1MB of memory consumption!

Bad Practice $description = $_post[' Description '];  Echo $description; echo $_post[' description '];   
41 using the Select Branch statement

switch, case better than using multiple if , else if statement, and code easier to read and Maintain.

42 Replace file, fopen, feof, fgets with file_get_contents

When you can use file_get_contents (),, and file() fopen() feof() fgets() Other series of methods, as far as possible, file_get_contents() because his efficiency is much higher! note, however, that the file_get_contents() PHP version is a problem when you open a URL file.

43 as much as possible to file operations, although the PHP file operation efficiency is not low44 Optimizing Select SQL statements

Do as little as possible insert update (on update, I have been bad).

45 using PHP intrinsic functions whenever possible46 loop Inside do not declare variables, especially large variables: objects

Does this seem to be more than just a matter of attention in php?

47 Multi-dimensional arrays try not to loop nested assignments48 cyclic with foreach more efficient

Try to use foreach substitution while and for circulation

50 pairs of global variables, should be exhausted unset () off51 is not a matter of object-oriented (OOP)

Object-oriented tends to be expensive, and each method and object invocation consumes a lot of memory.

52 methods do not subdivide too much

Think about what code you really want to reuse?

53 time-consuming functions are considered in the form of C extension

If there are a lot of time-consuming functions in your code, you might consider implementing them in C Extensions.

mod_deflate Compression Output

Open the Apache Mod_deflate module to improve the browsing speed of your web Pages. (mention of the echo big variable Problem)

55, The database connection should be turned off when used, do not use long connection56. split is faster than Exploade
Split () 0-0seconds (avg 0seconds)explode () 0-0seconds (avg 0Seconds) 

The above is all about, the following is the overall structure of the optimization of PHP performance:

2 overall structure optimizes PHP performance

1 upgrading PHP to the latest version

The simplest way to improve performance is to constantly upgrade and update the PHP Version.

2 using analyzers

There are a lot of reasons why websites are slow, and Web applications are extremely complex and confusing. And one possibility lies in the PHP code ITSELF. This parser can help you quickly find the code that is causing the bottleneck and improve the overall performance of your Site's Operations.

Xdebug PHP extension provides powerful features that can be used for debugging or for parsing Code. Allows developers to directly track the execution of scripts, real-time view of comprehensive Data. You can also import this data into the visual tool Kcachegrind.

3 Error Checking report

PHP supports a powerful error-checking feature that allows you to check for errors in real time, from more important errors to relatively small running tips. A total of 13 independent reporting levels are supported, and you can generate user-defined test reports based on these levels of flexible matching.

4 Leveraging Php's extensions

All along, we are complaining that PHP content is too complex, in recent years the developers made a corresponding effort to remove some of the redundant features of the Project. Even so, the number of available libraries and other extensions is Considerable. Even some developers are starting to think about implementing their own extension scenarios.

5 php cache, using PHP accelerator: APC

In general, PHP scripts are compiled and executed by the PHP engine, and are converted to machine language, also known as Opcode. If the PHP script has been compiled repeatedly to get the same result, why not skip the compilation process completely?

With the PHP accelerator, you can do this completely, caching the PHP Script's compiled machine code, allowing the code to execute immediately as required without the tedious compilation process.

For PHP developers, There are two available caching options, APC (alternative PHP cache, optional php buffer), which is an open source accelerator that can be installed through pear. Another popular scenario is Zend Server, which not only provides opcode caching techniques, but also provides caching tools for the corresponding Pages.

6 Memory Cache

PHP often plays an important role in retrieval and data analysis, which can lead to performance Degradation. In fact, some operations are completely unnecessary, especially from the database repeatedly retrieving some commonly used static Data. Consider a short-term use of redis or memcached extension to cache Data. Memcached's Extended Cache works with the libmemcached library, caches data in ram, and allows users to define the age of the cache, helping to ensure that user information is updated in real Time.

7 Content Compression

Almost all browsers support gzip compression, gzip can reduce the output of 80%, pay the price is about 10% increase in CPU Calculation. But what you earn is that not only does the bandwidth decrease, but your page loads quickly and optimizes the performance of your PHP Site. You can open it in Php.ini:

Onzlib.output_compression_level = (level)

Level may be a number between 1-9 and you can set different numbers so that he fits your Site.
If you use apache, you can also activate the Mod_gzip module, which he is highly customizable.

8 Server Cache

Mainly based on the Web reverse proxy static server Nginx and squid, as well as the apache2 mod_proxy and Mod_cache modules

9 Database optimization, caching, etc.

By configuring the database cache, such as opening the Querycache cache, when the query receives one and the same query, the server retrieves the results from the query cache, rather than parsing and executing the last query and data stored procedures, connection pooling technology, and so On.

PHP code optimization

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.