48 high-efficiency PHP optimization notation

Source: Internet
Author: User
Tags autoload explode php script zend

Source: Crooked Wheat Blog

Https://www.awaimai.com/1050.html

1 String

1.1 Less regular expressions

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.

str_replacepreg_replacethe function is much faster than the strtr function is faster str_replace .

Is there a useful function you missed?

For example: Strpbrk (), strncasecmp (), Strpos (), Strrpos (), Stripos (), Strripos ().

1.2 Character substitution

If you need to convert all of a single character, replace it with a string as the STRTR () function instead of an array:

"Efgh");        Array (//not recommended 

Efficiency improvement: 10 times times.

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

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!

Use strpos Find First (very fast), see if you need to replace, if necessary, then replace.

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

1.3 Compressing a large string

Use Gzcompress () and gzuncompress () to compress and decompress the large-capacity strings, and then deposit and remove the database.

This built-in function uses the GZIP algorithm to compress strings 90% .

1.4 Echo Output

echo strings are faster with commas instead of point connectors.

Although, echo is a language structure, not a real function.

However, it can pass multiple strings separated by commas as "function" arguments, so the speed is faster.

echo $str 1, $str 2;       //Fast echo $str 1. $str 2;      //speed slightly slower  

1.5 Use single quotes as much as possible

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 variables, and 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";                     ' string ';  

1.6 using Isset instead of strlen

When checking the length of a string, our first thought would be to 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 the function calls go through many steps, such as lowercase letters, hash lookups, which are executed with the called function.

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";}      

1.7 Splitting a string with split

It is split() faster to split the string explode() .

Split () 0-0seconds (avg 0seconds)explode () 0-0seconds (avg 0seconds) 

1.8 echo efficiency is higher than print

Because echo there is no return value, print an integral type is returned.

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.

2 Statements

2.1 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. Do not use in loops in particular @ .

In the 5 cycles of testing, even if the first use to error_reporting(0) turn off the error, the cycle is completed before opening, faster than the use @ .

2.2 Avoid using magic methods

__the functions that begin with are named Magic Functions, which are triggered under certain conditions.

These magic functions include: __construct() , __get() , __call() , and __autoload() so on.

__autoload()For example, if you cannot match the class name to the actual disk file, you will have to make a large number of file presence judgments.

It is well known that disk I/O operations are inefficient in determining the existence of a file that requires disk I/O operations, which is autoload why the efficiency of the mechanism is reduced.

Therefore, when designing a system, you need to define a clear set of mechanisms that map the class name to the actual disk file.

The simpler and clearer the rule, the higher __autoload() the efficiency of the mechanism.

autoloadMechanism is not a natural inefficiency, only misuse autoload , poorly designed automatic loading function, will lead to its efficiency reduction.

So, try __autoload to avoid the use of magic methods, to be discussed.

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

2.4 Using the ternary operator

In a simple judgment statement, the ternary operator is ?: more concise and efficient.

2.5 Using the Select Branch statement

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

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

If you are using a shared virtual host, php.ini cannot be modified, it is best to add the error_reporting () function.

Placed in the first line of each script file, or require_once() loaded, can effectively protect sensitive SQL queries and paths, and will not be displayed when an error occurs.

2.7 Non-functional segment label<?

Do not use the short form of the start flag, you are using such a symbol <? , you should use the full <?php start tag.

Of course, if the output variable, in <?= $value ?> this way is encouraged, can be more concise code.

2.8 Pure PHP code without end tag

If the file content is pure PHP code, it is best to remove the PHP end tag at the end of the file ?> .

This avoids having to accidentally add a space or line break after the PHP end tag, which causes PHP to start outputting these blanks, and there is no intention to output the script at this time.

2.9 Never use register_globals andmagic quotes

It was two very old features that might have been a good way at the time (ten years ago), but it does not seem to be the case now.

Older versions of PHP will open these two features by default when installed, which can cause security breaches, programming errors, and other problems.

Variables are created only when the user enters data.

PHP5.4.0 start these two functions are discarded, so every programmer should avoid the use.

If your past programs use both of these features, then get rid of them as soon as possible.

3 Functions

3.1 Use PHP intrinsics as much as possible

Built-in functions are implemented using the C language, and are optimized by PHP and are more efficient.

3.2 Using absolute paths

include require use absolute paths in and as far as possible.

If you include a relative path, PHP will traverse it to include_path find the file.

Using an absolute path avoids such problems, and it takes less time to parse the path.

3.3 Include files

Try not to use require_once and include_once include files, they are a process of judging whether a file is referenced, can not be used as much as possible.

And the use require , include method instead.

Brother Bird in his blog on many occasions, try not to use require_once and include_once .

3.4 Functions faster than class methods

A function that calls only one argument, and the function body is empty, takes the time equal to the 7-8 second $localvar++ operation.

The class method of the same function is approximately 15 $localvar++ operations.

3.5 Using subclass methods

The base class can only be reused, other functions are implemented in subclasses as much as possible, and the performance of the methods in subclasses is better than in the base class.

There is no relationship between the performance of class 3.6 and the number of methods

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

3.7 Read File contents

In the case can be used 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!

3.8 Reference Pass Parameters

Multiple return values of a function are implemented by means of a parameter address reference, which is more efficient than passing by value.

The method is to add one before the parameter variable & .

3.9 methods do not subdivide too much

Think about what code you really want to reuse?

3.10 Try to be static

If a method can be static, then declare it static, speed can be improved 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 methods and non-static methods is mainly distinguished in memory.

Static methods generate memory at the beginning of a program, and instance methods (non-static methods) generate memory in a program run.

Therefore, the static method can be called directly, the instance method must first genetic the instance to call again, the static speed is fast, but many will occupy the 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.

3.11 implemented in C extension mode

If you have a lot of time-consuming functions in your code, you might consider implementing them in the form of C extensions.

4 Variables

4.1 Destroying variables in time

Arrays, objects, and global variables make up the memory in PHP, which is caused by PHP's underlying Zend engine.

In general, the memory utilization of the PHP array is only 1/10 .

In other words, a 100M memory in the C language array, in PHP will be 1G.

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

4.2 Using the $_server variable

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

One is ready to use directly, and one needs the result of the function.

Creating local variables in the 4.3 method

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

4.4 Local variables are faster than global variables

Because local variables are present in the stack.

When a function occupies a stack space that is not very large, this part of the memory is likely to hit all the CACHE,CPU access efficiency is very high.

Conversely, if a function uses both global and local variables, the CPU cache needs to switch back and forth when the two addresses are large, and the efficiency will decrease.

4.5 Local variables instead of object properties

Create an object property (variables within a class, such as: $this->prop++ ) are slower than local variables 3 .

4.6 Declaring a local variable in advance

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

4.7 Caution declaring global variables

Declaring a global variable that is not used by any of the functions also degrades performance.

This is the same as declaring the same number of local variables, and PHP might check to see if the global variable exists.

4.8 Using ++$i increments

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

Keep in mind that this optimization is a good idea, because not all of the instruction optimizer will do the same optimization processing.

4.9 Do not randomly copy variables

Sometimes to make the PHP code neater, some novice php (including me) will copy the predefined variables into a variable with a shorter name.

In fact, the result is an increase in memory consumption, which will only make the program slower.

Imagine, in the following example, if the user maliciously inserted 512KB byte of text, it will cause 1MB of memory is consumed!

Bad Practice $description = $_post[' description '];  Echo $description; echo $_post[' description '];   

4.10 Loop Internal do not declare variables

Especially big variables, which seems to be more than just a question in PHP, right?

4.11 Be sure to initialize the variable

The "initialization" here refers to "declaration".

When a variable is not initialized, the PHP interpreter automatically creates a variable, but it is not a good idea to use this feature for programming.

This can cause the program to be rough or make the code confusing to others.

Because you need to find out where this variable is going to start being created.

In addition, incrementing an uninitialized variable is slower than initializing it.

So it would be a good idea to initialize the variables.

5 Arrays

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

Causes each pass argument to be a character instead of accepting the array as a find and replace parameter.

5.2 Array Element Quotes

$row[‘id‘]$row[id]7 times times faster than speed.

If the quotation marks are not quoted, for example $a[name] , then PHP will first check for constants that have no define definitions name .

If so, use this constant value as the array key value. If not, then look for ‘name‘ an array element with a key value of string.

The process of finding a judgment is more, so it is recommended to develop the habit of quoting the array key names.

As mentioned in the string section above, it is faster than using it " .

5.3 Multi-dimensional array operations

Multidimensional arrays try not to iterate over nested assignments.

5.4 Looping with foreach

Use substitution and recycling as much as possible foreach while for , more efficiently.

6 Architecture

6.1 Compression output

To turn on gzip compression in php.ini:

OnZlib.output_compression_level = (level)

levelThere may be a 1-9 number between, you can set a different number.

Almost all browsers support gzip compression, and gzip can reduce 80% the output.

The price paid is about 10% more CPU compute.

But it's still going to make it, because the bandwidth is reduced and the page loads faster.

If you use Apache, you can also activate the Mod_gzip module.

6.2 Statically-formatted pages

Apache/nginx the time to parse a PHP script is much slower than parsing a static HTML 2 page 10 .

So try to make the page static, or use static HTML pages.

6.3 Upgrading PHP to the latest version

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

6.4 Leveraging PHP's extensions

All along, everyone is complaining that PHP content is too complicated.

In recent years, developers have made a concerted effort to remove some of the redundancy features in 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.

6.5 PHP Cache

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 compiles the same results over and over again, why not skip the compilation process completely?

The PHP accelerator caches the compiled machine code, allowing the code to execute immediately as required without the tedious compilation process.

For PHP developers, there are two available caching scenarios.

One is APC (alternative PHP cache, optional PHP buffer), which is an open source accelerator that can be installed through pear.

Another popular scenario is opcode, the opcode caching technique.

6.6 Using the NoSQL cache

Either memchached or Redis can.

These are high-performance distributed memory object cache system, which can improve the performance of dynamic network application and reduce the burden of database.

This caching of arithmetic codes (OPcode) is also useful, so that the script does not have to recompile for each request.

Can follow the public number lovephp

48 high-efficiency PHP optimization notation

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.