In-depth analysis of PHP optimization and precautions, in-depth analysis of php Optimization
1. Static as much as possible:
If a method can be static, it is declared as static, and the speed can be increased by 1/4, or even increased by nearly three times during my testing.
Of course, this test method needs to be executed more than 100,000 times, and the effect is obvious.
In fact, the efficiency of static and non-static methods is mainly different in memory: static methods generate memory at the beginning of the program, and instance methods generate memory in the program running, so static methods can be called directly, the instance method must first generate an instance and call the method through the instance. The static speed is very fast, but the memory will be occupied when the instance is too large.
Any language is used for memory and disk operations. As to whether it is object-oriented, it is only a software layer problem. The underlying layer is the same, but the implementation methods are different. Static Memory is continuous, because it is generated at the beginning of the program, and the instance applies for discrete space, so of course there is no static method fast.
Static Methods always call the same memory. The disadvantage is that they cannot be destroyed automatically, but can be destroyed by instantiation.
2. The echo efficiency is higher than that of print. Because echo does not return a value, print returns an integer;
Test:
Echo0.000929-0.001255 s (average 0.001092 seconds) Print0.000980-0.001396 seconds (average 0.001188 seconds)
The difference is about 8%. In general, echo is faster.
Note: When the echo string is large, performance will be seriously affected if no adjustment is made. Use mod_deflate with apached enabled for compression or open ob_start to put the content into the buffer zone first.
3. Set the maximum number of cycles before the loop, not in the loop;
All fools understand the truth.
4. Destroy variables to release memory, especially large arrays;
Arrays and objects occupy the memory in php, which is caused by the zend engine at the underlying layer of php,
In general, the memory usage of PHP arrays is only 1/10. That is to say, an array of 100 MB memory in C language requires 1 GB in PHP.
Especially in the system where PHP is used as the backend server, the memory consumption is too high.
5. Avoid using magic methods such as _ get, _ set, and _ autoload;
For functions starting with _, they are named Magic functions, which are initially accessed under specific conditions. In general, there are several magic Functions
__construct(),__destruct(),__get(),__set(),__unset(),__call(),__callStatic(),__sleep(),__wakeup(),__toString(),__set_state(),__clone(),__autoload()
In fact, if _ autoload cannot efficiently match the class name with the actual disk file (note: this refers to the actual disk file, not just the file name, the system will have to determine whether a large number of files exist (which needs to be searched in the path contained in each include path), and determine whether a file exists through disk I/O operations, as we all know, the efficiency of disk I/O operations is very low, so this is the reason for reducing the efficiency of the autoload mechanism.
Therefore, in system design, we need to define a clear mechanism for ing Class names to actual disk files. The simpler and clearer the rule, the more efficient the autoload mechanism is.
Conclusion: The autoload mechanism is not a natural low efficiency. Only misuse of autoload and poor automatic loading functions can reduce the efficiency.
Therefore, we recommend that you avoid using the _ autoload magic method as much as possible.
6. requiere_once () is resource-consuming;
This is because requiere_once needs to determine whether the file has been referenced), so do not use it as much as possible. Avoid using the require/include method.
7. Use the absolute path in pair des and requires.
If it contains a relative path, PHP will traverse the file search in include_path.
Using an absolute path will avoid such problems, so it takes less time to parse the operating system path.
8. If you need to get the script execution TIME, $ _ SERVER ['requset _ time'] is better than time ();
As you can imagine. One is that the current achievements can be used directly, and the other is the result obtained by the function.
9. When using PHP internal strings to operate functions, try to use them instead of regular expressions, because the efficiency is higher than regular expressions;
Needless to say, regular expressions consume the most performance.
Are there any useful functions you missed? For example, when strpbrk () strncasecmp () strpos ()/strrpos ()/stripos ()/strripos () accelerates strtr,
Use strings instead of arrays for strtr:
<?php$addr = strtr($addr, "abcd", "efgh"); // good$addr = strtr($addr, array('a' => 'e', )); // bad?>
Efficiency Improvement: 10 times.
10. Replace str_replace is faster than replace preg_replace with regular expressions, but strtr is 1/4 faster than replace;
In addition, do not make unnecessary replacement. Even if it is not replaced, str_replace will allocate memory for its parameters. Very slow! Solution:
Use strpos to first find (very fast) and check whether replacement is required. If necessary, replace the efficiency:-If replacement is required: the efficiency is almost the same, with a difference of about 0.1%.
If you do not need to replace: Use strpos to speed up to 200%.
11. The parameter is a string
If a function can accept both arrays and simple characters as parameters, such as a character replacement function, and the parameter list is not too long, you can consider writing an additional replacement code, so that each passing parameter is a character, rather than accepting arrays as search and replacement parameters. Minor events, 1 + 1> 2;
12. It is best not to use @. Masking errors with @ will reduce the script running speed;
@ Actually has many operations in the background. Compared with @, the efficiency difference is 3 times. In particular, do not use @ in a loop. In five loop tests, even if the error is disabled with error_reporting (0), enabling it after the loop is completed is faster than using.
13. $ row ['id'] is 7 times faster than $ row [id]
We recommend that you use array keys and quotation marks;
14. Do not use functions in a loop
For example, For ($ x = 0; $ x <count ($ array); $ x), the count () function is calculated first. You know the reason.
16. The fastest speed to create local variables in the class method is almost as fast as calling local variables in the method;
17. Creating a global variable is twice slower than a local variable;
Because local variables exist in the stack, when the stack space occupied by a function is not very large, this part of memory may all hit the cache, And the CPU access efficiency is very high at this time.
On the contrary, if a function uses both global variables and local variables, the cpu cache needs to be switched back and forth when the two addresses differ greatly.
(I understand)
18. Create an object property (the variables in the class). For example, ($ this-> prop ++) is three times slower than the local variable;
19. Creating an undeclared local variable is 9-10 times slower than a defined local variable.
20. Declaring a global variable that has not been used by any function also reduces performance (the same as declaring the same number of local variables ).
PHP may check whether the global variable exists;
21. The performance of a method is irrelevant to the number of methods defined in a class.
Because I add 10 or more methods to the test class (these methods are before and after the test method), there is no performance difference;
22. The method in the subclass has better performance than in the base class;
23. it takes 7-8 times to run a function that calls only one parameter and the function body is empty $ localvar ++, and a similar method (function in the class) run the $ localvar ++ operation about 15 times;
24. replace double quotation marks with single quotes to include strings, which is faster.
Because PHP searches for variables in strings enclosed by double quotation marks, but not in single quotes.
The PHP engine allows single quotes and double quotes to encapsulate string variables, but there is a big difference! The double quotation mark string is used to tell the PHP engine to first read the string content, find the variable, and change it to The value corresponding to the variable. Generally, strings do not have variables, so using double quotation marks will lead to poor performance. It is better to use words.
String instead of double quotation marks.
BAD:$output = "This is a plain string";GOOD:$output = 'This is a plain string';BAD:$type = "mixed";$output = "This is a $type string";GOOD:$type = 'mixed';$output = 'This is a ' . $type .' string';
25. When the echo string is used, it is faster to replace the dot connector with a comma.
Echo is a "function" that treats multiple strings as parameters (echo is a language structure, not a real function, so double quotation marks are added to the function ).
For example, echo $ str1 and $ str2.
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.
28. Try to use the cache. memcached is recommended.
A high-performance distributed memory object cache system improves the performance of dynamic network applications and reduces the burden on databases;
It is also useful for the cache of OP code, so that the script does not have to re-compile each request.
29. Use the ip2long () and long2ip () functions to convert the IP address to an integer type and store it in the database instead of the primary type.
This can reduce storage space by almost 1/4. At the same time, it is easy to sort and quickly find the addresses;
30. Use checkdnsrr () to confirm the validity of some email addresses through domain name existence
This built-in function ensures that each domain name corresponds to an IP address;
31. Use the improved mysql _ * function mysqli _*;
32. Try to use the ternary operator (? :);
33. Whether PEAR is required
Before you want to completely redo your project, check if PEAR has what you need. PEAR is a huge resource library that many php developers know;
35. Use the error_reporting (0) function to prevent potential sensitive information from being displayed to users.
Ideal error reports should be completely disabled in the php. ini file. However, if you are using a shared virtual host and you cannot modify php. ini, you 'd better add the error_reporting (0) function and place it in the first line of each script file (or use
Require_once () to load) This effectively protects sensitive SQL queries and paths from being displayed when errors occur;
36. Use gzcompress () and gzuncompress () to compress () large-capacity strings (decompress) and store them in (retrieve) The database.
This built-in function can be compressed to 90% using the gzip algorithm;
37. Make a function have multiple return values by referencing the parameter variable address.
You can add "&" before the variable to indicate passing by address rather than by value;
38. fully understand the risks of magic reference 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. Use isset instead of strlen in some places
When operating on a string and checking whether its length meets certain requirements, you can 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 money in the top-level code that checks the string length.
40. Increase with ++ $ I
When incrementing or decrementing the value of the variable $ I ++ happens to be a tad slower then ++ $ I. this is something PHP specific and does not apply to other versions, so don't go modifying your C or Java code thinking it'll suddenly become faster, it won't. ++ $ I happens to be faster in PHP because instead of 4 opcodes used for $ I ++ you only need 3. post incrementation actually causes in the creation of a temporary var that is then incremented. while preincrementation increases the original value directly. this is one of the optimization that opcode optimized like Zend's PHP optimizer. it is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.
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, 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 services without command optimizers.
Provider (ISPs) and server.
40. Do not copy variables at will.
Sometimes, to make PHP code more clean, some new PHP users (including me) will copy the predefined variables to a variable with a shorter name, in fact, the result is a doubling of the memory consumption, which only slows down the program. In the following example, if a user maliciously inserts KB of text into the text input box, 1 MB of memory will be consumed!
BAD:$description = $_POST['description'];echo $description;GOOD:echo $_POST['description'];
41 use the select branch statement
Switch case is better than multiple if and else if statements, and the code is easier to read and maintain.
42. Replace file, fopen, feof, and fgets with file_get_contents.
When file_get_contents can be used to replace file, fopen, feof, fgets, and other methods, use file_get_contents as much as possible because of its high efficiency! Note the PHP version of file_get_contents when opening a URL file;
43. Perform as few file operations as possible, although PHP file operations are not efficient;
44. Optimize Select SQL statements and perform Insert and Update operations as little as possible (I have been maliciously approved in update );
45. Use PHP internal functions as much as possible
46. Do not declare variables inside the loop, especially large variables: Objects
(Isn't it just a matter of attention in PHP ?);
47. Do not use nested values for multi-dimensional arrays;
48. foreach is more efficient. Use foreach instead of the while and for loops;
49. "replace I = I + 1 with I + = 1. In line with the c/c ++ habits, high efficiency ";
50. For global variables, unset () should be used up;
51 is not an object-oriented (OOP). Object-oriented usually has a high overhead and each method and object call consumes a lot of memory.
52. Do not subdivide the methods too much. Think carefully about the code you actually intend to reuse?
53 if there are a large number of time-consuming functions in the code, you can consider using C extension to implement them.
54. Open the mod_deflate module of apache to speed up web page browsing.
(Mentioned the echo big variable problem)
55. When the database connection is used up, it should be switched off. Do not use persistent connections.
56. split is faster than exploade
split()0.001813 - 0.002271 seconds (avg 0.002042 seconds)explode()0.001678 - 0.003626 seconds (avg 0.002652 seconds)Split can take regular expressions as delimiters, and runs faster too. ~23% on average.