Some PHP performance optimization + my own opinions + explanations. PHP optimization for PHP is mainly for php. the main parameters in ini are adjusted and set properly. let's take a look at php below. some parameters in ini that have a major impact on performance should be optimized, such as PHP optimization and PHP optimization. the main parameters in ini are adjusted and set properly. let's take a look at php below. how to set parameters that have a greater impact on performance in ini.
# Vi/etc/php. ini
(1) disable finding PHP functions:
Disable_functions =
This option can be used to set which PHP functions are not allowed to be used. some functions in PHP are highly risky. you can directly execute some system-level script commands. if these functions are allowed to be executed, when a PHP program has a vulnerability, the loss is very serious! The recommended function settings are as follows:
Disable_functions = phpinfo, passthru, exec, system, popen, chroot, escapeshellcmd, escapeshellarg, shell_exec, proc_open, proc_get_status
Note: If your server contains PHP programs for system status detection, do not disable shell_exec, proc_open, proc_get_status, and other functions.
(2) find the PHP script execution time:
Max_execution_time = 30
This option sets the maximum execution time of the PHP program. if a PHP script is requested and cannot be executed within max_execution_time, PHP will not continue to run, A timeout error is returned directly to the client. If this option is not required, the default setting is 30 seconds. if your PHP script needs to be executed for a long time, you can increase the setting accordingly.
(3) Find the memory occupied by PHP script processing:
Memory_limit = 8 M
This option specifies the maximum memory occupied by PHP script processing. the default value is 8 MB. if your server memory is more than 1 GB, this option can be set to 12 MB for faster PHP script processing efficiency.
(4) PHP global function declaration:
Register_globals = Off
Many articles On PHP settings On the network recommend that you set this option to On. In fact, this is an extremely dangerous setting method, which may cause serious security problems. If you do not have special requirements, we strongly recommend that you keep the default settings!
(5) limit on the size of PHP files to be uploaded:
Upload_max_filesize = 2 M
This option sets the maximum file size that PHP can upload. the default value is 2 MB. You can increase the setting as needed.
(6) find the Session storage medium:
Session. save_path
If your PHP program uses Session dialogs, you can set the Session storage location to/dev/shm./dev/shm is a TMPFS file system exclusive to the Linux system, the file system uses the memory as the primary storage mode, which is better than RAMDISK because DISKSWAP can be used as a supplement and is a built-in function module of the system without additional configuration. Think about the speed from disk I/O operations to memory operations? Note that all data stored in/dev/shm is lost after the server is restarted. However, this is insignificant for the Session.
Due to the limited level, some still do not quite understand why. If you have better suggestions, feel free to add them!
0. replace double quotation marks with single quotes to include strings. this will be faster. Because PHP will search for variables in strings enclosed by double quotes, but not in single quotes. Note: Only echo can do this, it is a "function" that can treat multiple strings as parameters (echo is a language structure, not a real function, so double quotation marks are added to the function ).
PS: in single quotes, PHP does not automatically search for variables or escape characters, so the efficiency is much faster. In general, strings do not have variables, so using double quotation marks will lead to poor performance.
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.
PS: In fact, the speed of function, method, and static method is not significantly different. For details, see the article "implementation principle and performance analysis of PHP functions.
2. $ row ['id'] is 7 times faster than $ row [id.
PS: not quite familiar. it seems that only the latter will first determine whether the macro id exists. if it does not exist, it will be automatically converted to a string.
3. echo is faster than print, and multiple echo parameters are used to replace string connections, such as echo $ str1, $ str2.
PS: If echo $ str1. $ str2 is used, the PHP engine needs to connect all the variables first and then output them. echo $ str1, $ str2, the PHP engine will output them in sequence.
4. determine the maximum number of cycles before executing the for loop. do not calculate the maximum value for each loop. use foreach instead.
PS: operations like count and strlen are actually O (1), so there will be no too much consumption. of course, it is a good strategy to avoid computing every cycle. It is better to use foreach instead of for, which is more efficient. if you consider the consumption of foreach ($ array as $ var) each copy, you can use a reference like foreach ($ array as & $ var.
5. cancel unnecessary variables, especially large arrays, to release the memory.
PS: If you remember correctly, unset ($ array) will not immediately release the memory, but it is a good habit to release it at any time.
6. avoid using _ get ,__ set ,__ autoload whenever possible.
7. require_once () is expensive.
PS: require_once and include_once need to be judged seriously, so the efficiency is low, but the efficiency problem has been basically solved after version 5.2.
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.
PS: Supported. use iniset () as few as possible to set include_path.
9. if you want to know the TIME when the script starts to be executed (I .e. when the SERVER receives a client REQUEST), use $ _ SERVER ['request _ time'] instead of time ().
PS: $ _ SERVER ['request _ time'] saves the timestamp at which the REQUEST is initiated, while TIME () returns the Unix timestamp at the current time.
10. functions use the same functions instead of regular expressions.
PS: This function refers to strtok, strstr, strpos, str_replace, substr, explode, implode, and so on.
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.
PS: string operations are faster than regular expression replacement.
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.
PS: Considering the overhead differences between built-in functions and user-defined functions, I'm afraid this is not worth the candle.
13. Using the select branch statement is better than using multiple if and else if statements.
PS: switch in php supports numeric and string variables, which is better than switch in C. We recommend that you use it.
14. blocking error messages with @ is very inefficient and extremely inefficient.
PS: Is there any alternative? If you don't have one, you still have to use it ......
15. open the mod_deflate module of apache to speed up web page browsing.
16. when the database connection is used up, it should be switched off. do not use persistent connections.
PS: before connecting, it is best to set the corresponding timeout mechanism, such as connection timeout, read/write timeout, and wait timeout.
17. the error message is expensive.
18. increase the local variable in the method at the fastest speed. It is almost the same as calling a local variable 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 increasing a local variable ). PHP will probably check whether global variables exist.
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 methods in the derived class run faster than the same methods 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. Use static HTML pages and less scripts as much as possible.
27. unless the script can be cached, it will be re-compiled every time it is called. The introduction of 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 (the built-in data structure of C for storing PHP variables. However, because strlen () is a function, it is more or less slow, because function calling goes through 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 money in the top-level code that checks the string length.
PS: long-known.
30. 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 the post-increment mode. this temporary variable is then incremented. The pre-increment directly increases on the original value. This is a kind of optimization, as the Zend PHP optimizer does. 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.
31. object-oriented (OOP) is not required. object-oriented usually has a high overhead, and each method and object call consumes a lot of memory.
32. arrays are also useful instead of using classes to implement all data structures.
33. do not subscribe too many methods. think carefully about the code you are actually planning to reuse?
34. when you need it, you can always break down the code into methods.
PS: Appropriate methods should be used for decomposition, and methods with less frequently used rows should be written directly as much as possible, which can reduce the overhead of function stacks. method nesting should not be too deep; otherwise, the PHP operation efficiency will be greatly affected.
35. use as many built-in PHP functions as possible.
36. if there are a large number of time-consuming functions in the code, you can consider using C extension to implement them.
37. profile your code. The validator will tell you how much time the code consumes. The Xdebug debugger contains an inspection program, which can display the code bottleneck in general.
38. mod_zip can be used as an Apache module to instantly compress your data and reduce the data transmission volume by 80%.
39. 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;
PS: remember to use file_get_contents and file_put_contents whenever possible. you do not need to determine whether the file handle is successfully opened.
40. perform as few file operations as possible, although PHP file operations are not efficient;
41. optimize Select SQL statements and perform Insert and Update operations as little as possible (I have been maliciously approved in update );
42. 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 !);
PS: built-in functions are nearly an order of magnitude more efficient than user-defined functions.
43. do not declare variables inside the loop, especially big variables: objects (doesn't it seem to be a concern in PHP ?);
PS: This is required. when there are too many or too many variables, the overhead of each redistribution cannot be ignored.
44. do not use nested values for multi-dimensional arrays;
45. do not use regular expressions when using internal PHP strings to operate functions;
46. foreach is more efficient. use foreach instead of the while and for loops;
47. use single quotes instead of double quotes to reference strings;
PS: Dizzy. isn't that the first one?
48. replace I = I + 1 with I + = 1. In line with the c/c ++ habits, high efficiency ";
49. for global variables, unset () should be used up;
...