The article summarizes the optimization and optimization code in php, which provides php programmers with a good idea. 1. if you can define a class method as static, try to define it as static, it will increase the speed by nearly 4 times. 2. $ row [quot; idqu... the article summarizes the optimization and optimization code in php, which provides php programmers with a good idea.
1. if the class method can be defined as static, it should be defined as static as much as possible, and its speed will be increased by nearly four times.
2. $ row ["id"] is 7 times faster than $ row [id.
3. echo is faster than print, and multiple echo parameters are used instead of periods to replace string connections, such as echo $ str1, $ str2.
4. determine the maximum number of cycles before executing the for loop. do not calculate the maximum value for each loop. use foreach instead.
5. cancel unnecessary variables, especially large arrays, to release the memory.
6. avoid using _ get ,__ set ,__ autoload.
7. require_once () is expensive.
8. try to use the absolute path when you include the file, because it avoids PHP's speed of searching for the file in include_path, and it takes less time to parse the operating system path.
9. if you want to know the time when the script starts to be executed (I .e. when the SERVER receives the client request), use $ _ SERVER ["REQUEST_TIME"] instead of time ().
10. functions use the same functions instead of regular expressions.
11. the str_replace function is faster than the preg_replace function, but the strtr function is four times more efficient than the str_replace function.
12. if a string replacement function can take an array or character as a parameter and the parameter length is not too long, you can consider writing an additional replacement code so that each parameter passing is a character, instead of writing only one line of code to accept arrays as query and replacement parameters.
13. Using the select branch statement is better than using multiple if and else if statements.
14. blocking error messages with @ is very inefficient and extremely inefficient.
15. open the mod_deflate module of apache to speed up web page browsing.
16. the database connection should be closed when use is complete. do not use persistent connections.
17. the error message is expensive.
18. increasing local variables in a method is the fastest. it is almost the same as calling local variables in a function.
19. increasing a global variable is twice slower than increasing a local variable.
20. incrementing an object property (for example, $ this-> prop ++) is three times slower than incrementing a local variable.
21. increasing an unspecified local variable is 9 to 10 times slower than increasing a predefined local variable.
22. defining only one local variable without calling it in the function also slows down (to the extent that it is equivalent to incrementing by a local variable). PHP will probably check whether there is a global variable.
23. method calling seems to have nothing to do with the number of methods defined in the class, because I have added 10 methods before and after the test method, but the performance has not changed.
24. the method in the derived class runs faster than the same method defined in the base class.
25. calling an empty function with a parameter takes seven to eight times to increment local variables. similar method calls take nearly 15 times to increment local variables.
26. Apache parses a PHP script two to ten times slower than parsing a static HTML page.
27. unless the script can be cached, it will be re-compiled every time it is called. introducing a PHP Cache mechanism can generally improve the performance by 25% to 100%, so as to avoid compilation overhead.
28. use memcached as much as possible. memcached is a high-performance memory object cache system that can accelerate dynamic Web applications and reduce database load. it is useful for the cache of OP code, so that the script does not have to re-compile each request.
29. when operating a string and checking whether its length meets certain requirements, you will use the strlen () function. this function is executed quite quickly because it does not perform any calculations and only returns the known string length stored in the zval structure (C's built-in data structure, used to store PHP variables. however, because strlen () is a function, it is more or less slow, because function calls take many steps, such as lowercase letters, PHP does not distinguish between case-insensitive function names.) and hash searches are executed along with the called function. in some cases, you can use the isset () technique to accelerate your code execution.
(For example)
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 () is used as a language structure, this means that function search and lowercase letters are not required for execution. that is to say, in fact, you do not spend too much overhead in the top-level code that checks the string length.
34. when the execution variable $ I increments or decreases, $ I ++ is slower than ++ $ I. this difference is exclusive to PHP and does not apply to other languages. therefore, do not modify your C or Java code and expect them to become faster and useless immediately. ++ $ I is faster because it only requires three commands (opcodes), and $ I ++ requires four commands. in fact, a temporary variable is generated in post-increment mode, which is then incremented. the pre-increment directly increases on the original value. this is a kind of optimization processing, as the Zend PHP Optimizer has done. keeping this optimization processing in mind is a good idea, because not all command optimizers perform the same optimization and there are a large number of Internet service providers (ISPs) that do not have command optimizers) and server.
35. object-oriented (OOP) is not required. object-oriented usually has a high overhead, and each method and object call consumes a lot of memory.
36. arrays are also useful instead of using classes to implement all data structures.
37. do not subdivide the methods too much. think carefully about the code you actually intend to reuse?
38. when you need it, you can always break down the code into methods.
39. try to use a large number of PHP built-in functions.
40. if a large number of time-consuming functions exist in the code, you can consider using C extension to implement them.
41. profile your code. the validator will tell you how much time the code consumes. the Xdebug debugger contains an inspection program. The evaluation and inspection shows the code bottleneck in general.
42. mod_zip can be used as an Apache module to instantly compress your data and reduce the data transmission volume by 80%.
43. when file_get_contents can be used to replace file, fopen, feof, fgets, and other methods, try to use file_get_contents, because its efficiency is much higher! Note the PHP version of file_get_contents when opening a URL file;
44. perform as few file operations as possible, although PHP file operations are not efficient;
45. optimize Select SQL statements and perform Insert and Update operations as little as possible (I have been maliciously approved in update );
46. try to use PHP internal functions as much as possible (however, in order to find a function that does not exist in PHP, it is a waste of time to write a user-defined function. this is an empirical problem !);
47. do not declare variables inside the loop, especially big variables: objects (doesn't this seem to be a concern in PHP ?)
48. do not use nested values for multi-dimensional arrays.
49. do not use regular expressions when you can use PHP internal strings to operate functions.
50. foreach is more efficient. use foreach instead of while and for loops.
51. use single quotes instead of double quotes to reference strings
52. replace I = I + 1 with I + = 1. it conforms to the c/c ++ habit and is highly efficient.
53. for global variables, unset () should be used up.
Code Optimization instance
When an array is passed in a function
Using return is more efficient than using global
For example
Ratio
Efficient
2. (this code is used to obtain the URL corresponding to the program directory, which is recommended)
$urlarray=explode("/",$HTTP_SERVER_VARS["REQUEST_URI"]); $urlcount=count($urlarray);unset($urlarray[$urlcount-1]); $ofstarurl="http://".$HTTP_SERVER_VARS["HTTP_HOST"].implode("/",$urlarray);
Code comparison
$pre_urlarray=explode("/",$HTTP_SERVER_VARS["HTTP_REFERER"]); $pre_url=array_pop($pre_urlarray);
Efficient
3. when judging in a loop, it is more efficient to use constant to determine the value.
$ A = 2; $ B = 2;
For example
If ($ a ==$ B) $ c = $;
Ratio
If ($ a ===$ B) $ c = $;
Efficient
4. use where in to use less limit for mysql queries.
Limit queries the first few records of multiple records, which is fast, but the query speed is slow
Using in. the query of the continuity record is very fast. the first running of the non-continuity record will be a little slower, but it will be faster later!
5. the data operation stability of the NT Server is less than that of unix/linux
6. use ob_start () whenever possible before output to speed up the output speed. it is applicable to NT or nuli/linux. for unlix servers, if ob_start ("ob_gzhandler") is used, the output efficiency will be higher.
7. try to use if ($ a = his/her value) when determining whether to use if (empty ($ a) whenever possible, because the program runs faster.
8. when not supported! = Equivalent to <> efficiency
9. the efficiency of using $ a = "11111111111111" in personal experience is quite different from that in $ a = "11111111111111 ".
10. using standard SQL statements will facilitate MySQL parsing.
11. use
The instance code is as follows:
COOKIE will take effect immediately
If ($ online)
Setcookie ("online1", $ online, $ cookietime, $ ckpath, $ ckdomain, $ secure );
The COOKIE must be refreshed again to take effect.
12. use
The instance code is as follows:
Ratio
File ($ filename );
Excellent in both speed and stability
13. truncation of the string optimization function (can be avoided? Characters)
The instance code is as follows:
$length) { $num = 0; for ($i = 0; $i < $length - 3; $i++) { if (ord($content[$i]) > 127) $num++; } $num % 2 == 1 ? $content = substr($content, 0, $length - 4) : $content = substr($content, 0, $length - 3); $content.= "..."; } return $content;}?>
For example, $ newarray [1] = substrs ($ newarray [1], 25 );
14. case-sensitive shielding in the program
The instance code is as follows:
15. do not use file (); or do not use fget (); (unstable or slow) obtain an array function
The instance code is as follows:
", $filedata); $filedb = explode("
", $filedata); //array_pop($filedb); $count = count($filedb); if ($filedb[$count-1] == ''){unset($filedb[$count - 1]);} return $filedb; }?>
// This function has many codes, but it has great advantages in speed and stability!
Implement the preceding array separation code
In this way, it is very convenient to access the block data of tempArray.
The instance code is as follows:
Access and process code
The instance code is as follows:
$ Key) {$ this-> doSomeThing ($ ID ); // access the block array of tempArray $ array2 [$ Key] $ this-> doSomeThing2 ($ array2 [$ Key]);}?>
Permanent link:
Reprint at will! Include the article address.