PHP performance specifications

1 code optimization

1 of static as possible

If a method can be static, then declare it as static, 1/4 speed can be increased, even when I tested, this increased nearly threefold.

Of course, this test method requires the execution of more than one hundred thousand, the effect was obvious.

In fact, the efficiency of static methods and non-static method of the main differences in memory: the static method is generated when the program starts memory, an instance method (non-static method) to generate a memory in the program run, so you can directly call the static methods, instance methods first to Health examples recall, still fast, but more will account for memory.

Any language of memory and disk operations, as to whether object-oriented, just a matter of software layers, the bottom is the same, but different implementations. Static memory is continuous, because it is the beginning of the program is generated, while examples of the application of the method is discrete space, so of course not as fast as static methods.

Always call the static method, the drawback that they can not be destroyed automatically the same piece of memory, and can be instantiated destroyed.

2 echo print efficient than

Because echothere is no return value, printit returns an integer. test:

echo 
0 .000929 - 0 .001255 S (average 0 .001092 seconds The) Print 0 .000980 - 0 .001396 seconds The (average 0 .001188 seconds The)

A difference of about 8%, on the whole echois relatively fast.

Note: echothe output string of big time, if there is no adjustment will seriously affect performance. Open the Apache mod_deflatecompression, or open ob_startthe contents into the buffer can improve performance problems.

3 maximum number of loops

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

4 timely destruction variables

Arrays and objects in PHP particularly memory-intensive, this due to the underlying PHP zend engine caused. In general, memory utilization PHP array of one-tenth, that is to say, a 100M memory arrays in the C language, which is necessary in PHP 1G.

Especially in PHP system as a back-end server, the memory consumed much of a problem often occurs.

5 Avoid using as __get, __ set, __ autoload and other magic methods

(For reference only, open to question)

For __functions that begin with is named magic functions, such functions are triggered under certain conditions. Overall, the Magic are the following functions __construct(), __destruct(), __get(), , , , , , , , , , .__set()__unset()__call()__callStatic()__sleep()__wakeup()__toString()__set_state()__clone()__autoload()

In fact, if  not efficient class name and the actual disk file (note that this refers to the actual disk file, not just the file name) in association with, the system will have to do to determine whether the presence of a large number of files (requires each path include path included to look for), and determine whether a file exists to do disk I / O operations, well-known disk I / O operation efficiency is very low, so this is making the cause of reducing the efficiency of the mechanism.__autoload()autoload

Therefore, we in the system design, the need to define a clear set of mechanisms for the class name and the actual disk file mapping. This rule is more simple and more clear, autoloadefficient mechanisms will be.

Conclusion: The autoloadmechanism is not natural inefficiencies, only abuse autoload, poorly designed automatic loading function will lead to reducing its efficiency.

So try to avoid using magic methods, open to question.__autoload

6 requiere_once () and include_once () more consumption of resources

This is because requiere_once(), and include_once()need to determine whether the file is referenced, so I can not try to do. Common require/ includemethod avoids. Bird brother in his blog on many occasions declared try not to use require_onceand include_once.

7 use absolute paths include and require in

If you include a relative path, PHP will include_pathtraverse find files inside.
Absolute path will avoid such problems, and therefore the time required to resolve the OS paths less.

8 Use $ _SERVER [ 'REQUSET_TIME']

If you need to get the script execution time, superior .$_SERVER['REQUSET_TIME']time()

Imagine, one is ready to be used directly, the results also need a function derived.

9 alternative regular expression with built-in functions

Internal use case PHP string manipulation functions, try to use them, do not use regular expressions, because it is more efficient than regular.

I did not have to say, the regular consumption of most properties.

There is no useful function you missing? For example: The strpbrk () , strncasecmp () , the strpos () , strrpos () , stripos () , strripos () .

strtr ()  function is used to specify the character conversion, if all the time need to convert a single character, a string instead of an array:

<?php
$addr = strtr($addr, "abcd", "efgh");       // good
$addr = strtr($addr, array('a' => 'e', )); // bad

Efficiency gains: 10 times.

10 with strtr as character replacement

str_replaceReplace character than the regular replacement preg_replacefast, but strtrthan str_replacefast 1/4.

Also, do not do unnecessary replacement, even if not replaced, str_replacewill be a memory for parameter assignment. very slow!

The solution: use  strpos to find (very fast) to see if needs to be replaced, if necessary, and then replaced.

Efficiency: If you need to replace, efficiency is almost equal, the difference in   right and left. If you do not replace: with   fast  .0.1%strpos200%

11 string instead of an array as a parameter

If a function both accepts an array, but also to accept the simple character as a parameter, then try to use the character as a parameter. Such as character replacement functions, parameter list is not too long, consider writing a few redundant replacement code, so that each time a character is to pass parameters, rather than accept an array as the Find and Replace parameter. Trivialize,1+1>2 .

12 better not @

With @cover up mistakes will reduce the speed of the script, and there are many additional operations in the background. With @than not, the efficiency gap 3 times. Especially not in the loop @, in 5 test cycles, even with the first error_reporting(0)turn off the error, then the cycle is complete, open, than with @quickly.

13 array elements quotes

$row['id']Than the $row[id]speed seven times, it is recommended to develop an array of keys quoted habits.

14 Do not use inside the loop function

E.g:

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

The wording at the time of each cycle will call  count() the function, efficiency is greatly reduced, it is recommended this:

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

Let a function of the number of cycles to get out of the loop.

16 method in the establishment of local variables

The establishment of a local variable rate method in the fastest class, and almost calling a local variable in the method in as fast.

17 local variable 2 times faster than the global variables

Due to the existence of local variables on the stack, when a function stack space is not occupied by a lot of the time, this memory is likely to hit all the cache, this time the CPU access efficiency is very high.
Conversely, if a function in both the use of global variables and use a local variable, then when the large difference between these two addresses, cpu cache switching back and forth, then the efficiency drops.

18 local variable instead of object properties

Establishing an object property (which class variables, for example: $this->prop++) slower than 3 times the local variables.

19 advance to declare local variables

The establishment of an undeclared local variables than the already defined a local variable is slower than 9-10 times.

20 declare global variables with caution

A statement is not a function of any global variables used also degrade performance (and the same number of declarations local variables). PHP possible to check the global variable exists.

Performance class number 21 and it does not matter which method

After 10 or more newly added to the test method of the class, no difference in performance.

22 performance is superior subclass method in the base class

23 functions faster than a class method

Only one call parameter, and the time function of the function body is empty, is equal to 7-8 times the cost $localvar++calculation method of the same functional class of about 15 $localvar++operations.

24 instead of single quotes will be faster with double quotes

Because PHP looks for variables inside of double quotes, the single quotation marks will not.

PHP engine allows the use of single and double quotes to encapsulate the string variable, but they are very different rate of! Use double quotes string will tell the PHP engine, the first to read the contents of the string, variable find them, and instead of the corresponding value of the variable. Generally there is no string variables, so the use of double quotes will result in poor performance. Preferably the connection string instead of double-quoted strings.

the Output = $ "This IS A Plain String";   // bad practice 
$ the Output = 'This IS A Plain String';   // good practice 
 $ of the type = "Mixed"; // bad practice the Output = $ " A $ IS type String This "; $ type = 'Mixed'; // Output = good practice $ 'This IS A' $ type.. 'String';

25 echo string comma instead of point connector faster

echoYou can take several strings separated by commas as a "function" parameter passing, so the speed will be faster. (Note: echois a language construct, not a real function, add function so that the double quotes). E.g:

echo $ str1, $ str2;        faster speed //
 echo $ str1 $ str2;.       // slower pace

26 Try to static

Apache / Nginx A PHP script than a static HTML page 2-10 times slower, so try to make static pages, or static HTML pages.

28 Use Cached

Memchached or Redis can be.

High-performance, distributed memory object caching system to improve the dynamic performance of network applications, reduce the burden on the database.

Also cached on the operation code (OP code) is useful so that the script does not have to recompile for each request.

29 using integer save IP

Use ip2long()and long2ip()the IP address of the function transformed into an integer, and then stored in the database, and the stored non-character.

It's almost a quarter of the storage space can be reduced. At the same time can easily sort and addresses quickly find;

30 check email validity

Use with checkdnsrr () to confirm the validity of the email address by the presence of the domain name, this function can be built to ensure that each domain name corresponds to an IP address.

31 Using MySQLi or PDO

mysql_*Function has not been recommended, it recommended enhanced mysqli_*series of function or directly using PDO.

Try 32 like the ternary operator (? :)

33 whether components

Before you want to completely redo your project and see if there are ready-made components (in Packagist available on), by composer installation. Components someone else has made a good wheels, is a huge resource library, a lot of php developers know.

35 shield the sensitive information

Using the error_reporting () function to prevent potentially sensitive information to the user.

Ideal error reporting should be completely disabled in the php.ini file. But if you are using a shared web hosting, php.ini you can not change, then you'd better add error_reporting () function, in the first line of each script file (or use require_once () to load) which is effective protect sensitive SQL queries and path is not displayed when an error occurs;

Large compression string 36

Use gzcompress () and gzuncompress () of the string a large capacity compression / decompression, and then deposited into / extraction database. This built-in algorithm function using gzip, compressible string 90%.

37 ref parameter

Reference parameter the address to make a plurality of function return values, add "&" represents the variable parameters before transmission by address, not passed by value.

38 references fully understand the magic dangerous and SQL injection.

Fully understand “magic quotes” and the dangers of SQL injection. I’m hoping that most developers reading this are 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 the need to check the operating string and its length meets certain requirements, you assume that you would use strlen () function. This function is pretty fast, because it does not do any calculations, returns only zvalthe known length of a string structure (C built-in data structures used to store variables in PHP). However, due to strlen()a function, it is still somewhat slow because the function call requires several steps, such as lowercase letters (Annotation: refers to the lowercase name of the function, PHP function names are not case-sensitive), the hash lookup followed by performed together function calls. In some cases, you can use the isset () technique to accelerate the execution of your code.

E.g:

if (strlen($foo) < 5) {
    echo "Foo is too short";
}

// 使用isset() if (!isset($foo{5})) { echo "Foo is too short"; }

40 Use ++ $ i is incremented

When performing variable $iwhen increasing or decreasing, $i++than slower. This is something PHP specific and does not apply to other languages, so please do not go modifying your C or Java code thinking it'll suddenly become faster, useless. Faster is because it only requires three instructions (opcodes), you need four instructions. Postincrement will actually generate a temporary variable, this temporary variable is then incremented. The pre-incrementation increases the original value directly. This is one of the optimization process, so as Zend's PHP optimizer made. Remember that this optimization would be a good idea, since not all opcode optimizers do the same optimization, and there are Internet service providers (ISPs) without an opcode optimizer a lot and servers.++$i++$i$i++

40 Do not copy variables

Sometimes PHP code to make more clean, some PHP novice (including me) will copy the predefined variable to a good name is more variable in short, in fact, the result of this is increased memory consumption doubled, will only make program more slowly. Just look at the following example, if a malicious user to insert text 512KB byte text input box, which would lead to 1MB of memory to be used!

// bad practice 
$ Description = $ _POST [ 'Description'];
 echo $ Description; // good practice echo $ _POST [ 'Description'];

Use select statements 41

switch, caseBetter than the use of multiple if, statements, and the code easier to read and maintain.else if

42 Alternatively file, fopen, feof with file_get_contents, fgets

In can be used file_get_contents () replacement file(), fopen(), feof(), fgets()and other case series method, try to use file_get_contents()as much of his high efficiency! But be careful, file_get_contents()PHP version of the problem in time to open a file URL.

43 Try fewer file operations, although PHP file operation efficiency is not low

44 Select SQL statement optimization

Is carried out in as little as possible insert, updatethe operation (in the update, I was too bad batches).

45 as much as possible the use of PHP internal function

46 Do not declare variables inside the loop, especially the large variable: Object

It just does not seem to pay attention to inside PHP problem, right?

47 multidimensional array try not to assign nested loop

Foreach loop 48 with a higher efficiency

Try to use foreachin place whileand forloop

50 pairs of global variables should be spent on the unset () off

51 do not necessarily target-oriented (OOP)

Object-Oriented often much overhead, each method and object call consumes a lot of memory.

52 methods do not subdivide too much

Think you really re which code?

53 time-consuming function to consider manner as C extensions

If there is time consuming functions in your code, you can consider them as C extensions.

54 mod_deflate compressed output

Mod_deflate open the apache module, you can increase Web browsing speed. (Mentioned problem echo large variables)

55, when the database connection should be switched off after use, do not use the long connection

56, split faster than exploade

split()
0.001813 - 0.002271 seconds (avg 0.002042 seconds) explode() 0.001678 - 0.003626 seconds (avg 0.002652 seconds)

Above all about, here is the optimization of PHP performance from the structure as a whole:

2 overall structure optimization PHP performance

 

1 to upgrade to the latest version of PHP

The easiest way to improve performance is to constantly upgrade, update PHP version.

Use analyzer 2

The reason the site is running slow a lot, Web applications extremely complex, confusing people. One possibility is that while PHP code itself. The analyzer can help you quickly identify the code bottlenecks and improve the overall performance of site operations.

Xdebug PHP extension provides a powerful feature that can be used to debug, it can also be used to analyze the code. Easier for developers to directly track the execution of the script, view real-time integrated data. This data may also be introduced into the KCachegrind visualization tool.

3 inspection report error

PHP supports powerful error detection function, allowing you to check for errors in real time, the more important tips from error to a relatively small operation. Supports a total of 13 kinds of independent reporting level, you can flexibly matched these levels, generate user-defined test reports.

4 using the PHP extension

All along, everyone is complaining about PHP content is too complicated, in recent years developers have made appropriate efforts to remove some of the redundancy features of the project. Even so, the number of available libraries and other extensions is still very impressive. Even some developers began to consider the implementation of their expansion program.

5 PHP caching with PHP accelerator: APC

Under normal circumstances, the implementation of the PHP engine PHP script is compiled, it will be converted into machine language, also known as the opcode. If after repeated compiled PHP scripts and get the same results, why not skip the compilation process it completely?

By PHP accelerator, you can achieve this, it caches the compiled machine code after the PHP script that allows code execution immediately upon request, without going through the cumbersome process of compilation.

For PHP developers, currently offers two available caching options, one is APC (Alternative PHP Cache, optional PHP Cache), which is an open source can be installed by PEAR accelerator. Another popular program is Zend Server, it not only provides an opcode cache technology, but also provides a corresponding page caching.

6 Memory Cache

PHP usually plays an important role in the retrieval and data analysis, these operations may result in reduced performance. In fact, some action is completely unnecessary, especially repeatedly retrieve some common static data from the database. You may wish to consider short-term use Redis or Memcached extension to cache data. Memcached caching and libMemcached library expansion work, the data in RAM cache, the cache also allows user-defined period of time, helping to ensure real-time updates of user information.

7 content compression

Almost all browsers support Gzip compression methods, gzip could reduce the output of 80%, at the cost of an increase of about 10% of the cpu computation. But not only earned the bandwidth consumed is reduced, and your page loads quickly becomes optimize the performance of your PHP site. You can open it in PHP.ini in:

zlib.output_compression = On
zlib.output_compression_level = (level)

level may be a number between 1-9, you can set different numbers make him fit your site.
If you use apache, you can also activate mod_gzip module, he is highly customizable.

8 server cache

Mainly based on static web reverse proxy server nginx and squid, as well as the apache2 mod_proxy module and mod_cache

9 database optimization, caching, etc.

By configuring the database cache, such as cache QueryCache open, when a query is received and before the same query, the search result cache server will query species, rather than re-analysis and the last execution of the query and a data storage process, connection pool technology .


 

Guess you like

Origin www.cnblogs.com/sunsky303/p/12463925.html