Introduction to the methods of efficiency improvement and optimization in PHP

Source: Internet
Author: User
Tags glob php programming switch case
In view of the lessons of the Mini project, many places are not standard enough and inefficient. Therefore, in the further study of PHP, combined with Internet resources on the knowledge of PHP to do a certain summary, in order to avoid detours.

PHP, is the abbreviation of the English hypertext preprocessing language hypertext preprocessor. PHP is an HTML embedded language, is a server-side implementation of embedded HTML document scripting language, language style has similar to C language, is widely used.

PHP's unique syntax mixes the syntax of C, Java, Perl, and PHP's own creation. It can execute Dynamic Web pages more quickly than CGI or Perl. PHP is a dynamic page compared to other programming languages, PHP is to embed the program into the HTML document execution, execution efficiency than the full HTML markup of the CGI is much higher; PHP can also execute compiled code, compile can achieve encryption and optimize the code to run, so that the code runs faster.

Some summary of PHP programming:

0. It is quicker to use single quotes instead of double quotes to contain strings. Because PHP will search for variables in a string surrounded by double quotes, single quotes will not, note: only echo can do this, it is a string can be used as a parameter of the "function" (in the PHP manual that echo is a language structure, not a real function, so the function with double quotation marks).

1, if the method of the class can be defined as static, as far as possible to define as static, it will increase the speed of nearly 4 times times.

2. The speed of $row [' ID '] is 7 times times that of $row[id].

3. Echo is faster than print, and uses Echo's multiple parameters (referring to commas instead of periods) instead of string connections, such as Echo $str 1, $str 2.

4. To determine the maximum number of cycles before executing a for loop, do not calculate the maximum value once per cycle, preferably using foreach instead.

5. Unregister those unused variables, especially large arrays, in order to free up memory.

6, try to avoid the use of __get,__set,__autoload.

7, require_once () expensive.

8, include files as far as possible to use absolute path, because it avoids PHP to include_path to find the speed of the file, parsing the operating system path takes less time.

9. If you want to know when the script starts executing (that is, the server side receives the client request), use $_server[' request_time '] better than time ().

10, function instead of regular expression to complete the same function.

11, the Str_replace function is faster than the Preg_replace function, but the efficiency of the STRTR function is four times times the Str_replace function.

12, if a string substitution function, can accept an array or character as a parameter, and the parameter length is not too long, then you can consider an extra piece of replacement code, so that each pass argument is a character, rather than write a line of code to accept the array as the query and replace parameters.

13. Use the Select Branch statement (that is, switch case) better than using multiple if,else if statements.

14. Masking error messages with @ is extremely inefficient and extremely inefficient.

15, open the Apache mod_deflate module, can improve the browsing speed of the page.

16, the database connection should be turned off when used, do not use long connection.

17. Error messages are costly.

18, increment the local variable in the method, the speed is the quickest. is almost equivalent to the speed at which local variables are called in the function.

19, incrementing a global variable is twice times slower than incrementing a local variable.

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

21. Incrementing an undefined local variable is 9 to 10 times times slower than incrementing a pre-defined local variable.

22. Defining only a local variable without calling it in the function also slows down the speed (which is equivalent to incrementing a local variable). PHP will probably check to see if there are global variables.

23. The method invocation appears to be independent of the number of methods defined in the class, because I added 10 methods before and after the test method, but there was no performance change.

24. A method in a derived class runs faster than the same method defined in the base class.

25. Call an empty function with one parameter, which takes the same amount of time as performing a local variable increment operation of 7 to 8 times. A similar method call takes a time close to 15 local variable increment operations.

26, Apache parsing a PHP script time is 2 to 10 times times slower than parsing a static HTML page. Use static HTML pages as much as possible and use fewer scripts.

27. Unless the script can be cached, it will be recompiled every time it is called. Introducing a set of PHP caching mechanisms can typically improve performance by 25% to 100% to eliminate compilation overhead.

28, try to do the cache, you can use memcached. The memcached is a high-performance memory object caching system that can be used to accelerate dynamic Web applications and reduce database load. Caching of the OP code is useful so that the script does not have to recompile for each request.

29. 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 length of the known string stored in the Zval structure (the built-in data structure of C for storing PHP variables). However, because strlen () is a function, it is somewhat slower, because function calls go through a number of steps, such as lowercase letters (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.

(Example below)

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

(compare with the following tips)

if (!isset ($foo {5})) {echo "Foo is too Short" $$}

Calling Isset () happens to be faster than strlen (), because unlike the latter, Isset (), as a language structure, means that its execution does not require function lookups and lowercase letters. In other words, you're actually not spending much overhead in the top-level code that examines the length of the string.

30, the file lock function flock--constant parameters.

Shared lock (read operation)--lock_sh

Exclusive lock (write operation)--lock_ex

Release locks (whether shared or exclusive)--lock_un


The lock operation can be released through the fclose () function.

31. Verify that the string is a legitimate IP:

No regular, direct use of Ip2long (), legal return number, the law returns false.

32, PHP 5.3 Start, you can use __dir__ to get the current script directory, no longer realpath (__file__).

33, using CHECKDNSRR () through the existence of the domain name to confirm the validity of some email address

This built-in function ensures that each domain name corresponds to an IP address;

34. When the increment or decrement of the variable $i is executed, $i + + will be slower $i than + +. 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. + + $i is faster because it requires only 3 instructions (opcodes), $i + + requires 4 instructions. 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.

35, not the object-oriented (OOP), object-oriented tends to be very expensive, each method and object calls will consume a lot of memory.

36, not to use the class to implement all the data structure, arrays are also useful.

37, do not subdivide the method too much, think carefully about what you really want to reuse what code?

38, when you need, you can always break down the code into methods.

Decomposition into a method to be appropriate, less frequent use of the method as far as possible to write code directly, you can reduce the function stack overhead, and the method nesting should not be too deep, otherwise greatly affect the efficiency of PHP operation.

39, try to use a large number of PHP built-in functions.

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

41. Evaluate the test (profile) of your code. The inspector will tell you what parts of the code are consuming time. The Xdebug debugger contains an inspection program that can show the bottleneck of the code in general.

42, Mod_zip can be used as Apache module, to compress your data instantly, and to reduce the data transfer volume by 80%.

43, in the case can be replaced with file_get_contents file, fopen, feof, Fgets and other series of methods, as far as possible with the file_get_contents, because his efficiency is much higher! File_get_contents does not need to determine whether the file handle opened successfully. But pay attention to the PHP version of file_get_contents when opening a URL file;

44, as far as possible to file operations, although PHP file operation efficiency is not low;

45, optimize the Select SQL statement, as far as possible, as little as possible to insert, update operation (on the update, I was a bad batch);

46, as far as possible the use of PHP internal functions (but I have to find a php non-existent function, wasted can write a custom function time, experience problem Ah!) );

47, the loop inside do not declare variables, especially large variables: objects (this does not seem to be the only thing in PHP to pay attention to it?) );

48, multidimensional arrays try not to loop nested assignment;

49, in the case of PHP internal string manipulation function, do not use regular expressions;

50, foreach more efficient, try to use foreach instead of while and for loop;

51. Use single quotation marks instead of double quotation marks to reference strings;

52, "Replace I=i+1 with I+=1." In line with C + + habits, efficiency is high ";

53, to global variables, should be used up on unset () off;

54. The curly brace "{}" can manipulate the string like the "[]" action Array to obtain the character at the specified position.

55, PHP Tag "<?php?>" in a standalone PHP script can not write the end tag, this is to avoid accidental whitespace caused by the output and error. You can use annotations to indicate the end of the script.

56. Echo is a grammatical structure, not a function. With multiple strings followed by commas "," the efficiency is better.

57. In the array, 1, ' 1 ', and true are all cast to 1 when indexed. The ' 01 ' will not be converted and will be treated as a string.

58, a class of code written in different PHP tags is not legal, will report a syntax error. But the function is fine.

59. The difference and relationship between session and Cookie.

The session is saved on the server and the cookie is stored on the client's browser;

Session save can be file on hard disk, database, Memcached,cookie can be saved to hard disk (persistent cookie) and memory (session cookie);

There are two ways to pass a session_id, one is a cookie, and the other is a Get method (you can specify the name of the variable that holds the session_id by the configuration item).

60, get the current timestamp with $_server[' request_time ' instead of time (), you can reduce the function call, more efficient.

61, use _request to be cautious, _request get the data priority is E (NV) G (ET) P (OST) C (Ookie) S (ession), if the variable name, may cause high-priority data to be overwritten by low-priority data.

62, the header () function to exit, otherwise the code will be executed later.

63, Large array with reference to pass, reduce memory consumption, run out of unset ().

64, Set_time_limit () limitations. You can only limit the run time of the script itself, for example: System () functions, stream operations, database queries, and so on, for external execution time.

65, the difference between Echo,print,print_r,var_dump,var_export:

Echo,print is a syntax structure, not a function, and can only display the basic type, cannot display the array and the object, the other is the function, can display the array and the object;

echo can display multiple variables, separated by commas;

Print_r the second parameter can determine whether the output variable or the variable as the return value;

Var_dump prints the details of the variable, such as length and type, and can pass multiple variables as parameters;

Var_export returns a valid PHP code format.

66, Verification Email: filter_var ($email, Filter_validate_email);

67. How to obtain the file name extension:

One, PathInfo ($filename), take the value of EXTENSION, or PathInfo ($filename, pathinfo_extension).

Two, end (explode ('. ', $filename)).

68, try to like to use the ternary operator (?:);

69. Use the error_reporting (0) 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 (0) 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;

70. Do not copy variables randomly

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: $description = $_post[' description '];echo $description; Good:echo $_post[' description '];

1. When you can use file_get_contents instead of file, fopen, feof, Fgets and other series of methods, try to use file_get_contents, because his efficiency is much higher! But pay attention to the PHP version of file_get_contents when opening a URL file; 2. As much as possible to file operations, although PHP file operation efficiency is not low; 3. Optimize the Select SQL statement and, where possible, minimize the INSERT, Update operation (I was ill-granted on update); 4. Use PHP intrinsics as much as possible (but I'm wasting the time that could have written a custom function in order to find a function that doesn't exist in PHP, experience problem!) ); 5. Do not declare variables in the loop, especially large variables: objects (This is not just a question to be aware of in PHP?). ); 6. Multidimensional arrays do not loop nested assignments as much as possible, 7. Do not use regular expressions if you can use PHP internal string manipulation functions, 8.foreach is more efficient, try to use foreach instead of while and for loops, 9. Use single quotes instead of double quotation marks to refer to strings; 10. " Replace i=i+1 with I+=1. In line with the custom of C + +, the efficiency is high "; 11. For global variables, unset () should be exhausted; here's an article on improving PHP efficiency

Squeeze dry PHP to improve efficiency

This essay is translated and collated from the network of documents (see the last reference), especially Ilia Alshanetsky (most admired) in a number of PHP conference lectures, mainly in various types of improving PHP performance skills. In order to be precise, many parts have detailed efficiency data, as well as the corresponding version and so on. Lazy, the data will not be given, directly to the conclusion. ========================================================

Statically called members must be defined as static (PHP5 only)

Tip: PHP 5 introduces the concept of static members, which is consistent with the internal static variables of PHP 4, but is used as a member of the class. Static variables are similar to Ruby's class variables (class variable), and instances of all classes share the same static variable.

Quote:class Foo {function bar () {  echo ' Foobar ';}} $foo = new Foo;//instance $foo->bar ();//static Oo::bar ();

Static calls to non-static members are more efficient than static calls to the static member 50-60%. Mainly because the former will produce e_strict warning, internal also need to do conversion. ========================================================

Using class Constants (PHP5 only)

Tip: PHP 5 is a new feature, similar to the const C + +. The benefits of using class constants are:-compile-time parsing, no extra overhead-the hash table is smaller, so the internal lookup is faster-class constants exist only in a specific "namespace", so the hash name is shorter-the code is cleaner and makes debugging easier =================================== ===================== (temporarily) do not use Require/include_once require/include_once will open the target file every time it is called! -If you use the absolute path, PHP 5.2/6.0 does not have this problem-the new APC cache system has solved this problem file I/O increase/decrease efficiency if necessary, you can check whether the file has been require/include. Do not use functions when you do not invoke meaningless functions that have corresponding constants.

Quote:php_uname (' s ') = = Php_os; Php_version () = = Php_version; Php_sapi_name () = = Php_sapi;

Although the use is not much, but the efficiency increase about 3,500%. The fastest Win32 check $is _win = Directory_separator = = ' \ '; ========================================================

-No function

-Win98/nt/2000/xp/vista/longhorn/shorthorn/whistler ... Universal-Always available time problem (php>5.1.0 only) How do you know the time in your software? Simple, "time () time () again, you ask me...". But it will always call the function, slow. Now, with $_server[' Request_time ', you don't have to call the function and save it.

Accelerated PCRE

-For the results without saving, do not use (?). This way PHP does not allocate memory for conforming content, save. Improve efficiency by about 15%. -Can not use regular, do not use the regular, in the analysis of the time carefully read the manual "String function" section. Is there a useful function you missed? For example:

STRPBRK () strncasecmp () Strpos ()/strrpos ()/stripos ()/strripos ()


Accelerated STRTR

If you need to convert all of a single character, use a string instead of an array to do

STRTR:   $addr = STRTR ($addr, "ABCD", "EFGH");//Good $addr = Strtr ($addr, Array (' a ' = = ' e ',//.));//Bad

Efficiency improvement: 10 times times. ========================================================

Don't make unnecessary substitutions.

Even if there is no substitution, str_replace allocates memory for its parameters. Very slow! WORKAROUND:-Find First (very fast) with Strpos, see if there is a need to replace, if necessary, replace efficiency:-If necessary replace: the efficiency is almost equal, the difference is about 0.1%. -If you do not need to replace: Use Strpos fast 200%. ========================================================

The Evil @ operator

Do not abuse the @ operator. Although @ seems simple, there are actually many operations in the background. With @ than without @, efficiency gap: 3 times times. In particular, do not use @ in the loop, in the 5-cycle test, even if the first use of error_reporting (0) to turn off the error, after the cycle is completed and then open, than with @ faster. ========================================================

Use strncmp

When you need to compare the "first n characters" is the same time, with strncmp/strncasecmp, not substr/strtolower, not PCRE, not to mention Ereg. STRNCMP/STRNCASECMP is the most efficient (though not much high). Caution With Substr_compare (PHP5 only), according to the above, Substr_compare should be compared to the first substr faster. The answer is no, unless:-Ignoring case comparisons-larger strings do not use constants instead of strings why:-Need to query a hash table two times-need to convert a constant name to lowercase (when making a second query)-Generate E_notice warning-Creates a temporary string efficiency difference: 70 0%. ========================================================

Do not place the count/strlen/sizeof in the conditional statement for the For Loop

Tip: A classic approach

Quote:for ($i = 0, $max = count ($array); $i < $max; + + $i);?>

Efficiency increase relative to:-Count 50%-strlen 75% ========================================================

Short code is not necessarily fast

Longest if ($a = = $b) {$str. = $a;} else {$str. = $b;}//longer if ($a = = $b) {$str. = $a;} $str. = $b; Short $str. = ($a = = $b? $a: $b);

Which one do you think is fast? Efficiency comparison:


Incredible? One more:

  Original $d = Dir ('. ');   while ($entry = $d->read ())!== false) {if ($entry = = '. ' | | $entry = = ' ... ') {continue;} }   //Versus Glob ('./* ');   Versus (include. and.) Scandir ('. ');

Which one is fast? Efficiency comparison:-Original:3.37-glob:6.28-scandir:3.42-original without OO:3.14-SPL (PHP5): 3.95 VoiceOver: You can also see that PHP5 object-oriented Efficiency has been improved a lot, and the efficiency is not much worse than the pure function. ========================================================

Improve the efficiency of PHP file access

When you need to include other PHP files, use the full path, or the relative path that is easy to convert.

Include ' file.php '; Bad approach incldue './file.php '; Good include '/path/to/file.php '; Ideal


Best Use

PHP has a lot of extensions and functions available, before you implement a feature, you should see if PHP has this feature? Is there a simpler implementation?

$filename = "./somepic.gif"; $handle = fopen ($filename, "RB"); $contents = Fread ($handle, FileSize ($filename)); Fclose ($handle); vs. much simpler file_get_contents ('./somepic.gif ');


Tips on quoting

References can:-simplifies access to complex structural data-optimizes memory usage

$a [' B '] [' c '] = array (); Slow 2 extra hash lookups per access for ($i = 0; $i < 5; + + $i) $a [' B '] [' C '] [$i] = $i; Much faster reference based approach $ref =& $a [' B '] [' C ']; for ($i = 0; $i < 5; + + $i) $ref [$i] = $i;?> $a = ' large string '; Memory Intensive Approach function A ($STR) {return $str. ' Something ';}//More efficient solution function A (& $STR) {$str. = ' Something ';}   25th, 2009Comments
Related Article

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