PHP code Optimization 24 Canon

Source: Internet
Author: User
Tags foreach arrays php file php and php code strlen switch case how to use sql

echo is faster than print.
Use Echo's multiple parameters instead of string concatenation.
To determine the maximum number of loops before executing the FOR loop, do not compute the maximum value per loop, preferably by using foreach instead.
For global variables, the unset () should be used out.
It is quicker to use single quotes instead of double quotes to contain strings. Because PHP searches for variables in a string enclosed in double quotes, single quotes do not.
function to accomplish the same function instead of a regular expression.
$i + + $i slower than + + when the execution variable $i is incremented or decremented. This difference is specific to PHP and does not apply to other languages, + + $i faster because it requires only 3 instructions (opcodes), $i + + requires 4 instructions. A post increment actually produces a temporary variable, which is then incremented. And the predecessor increment increases directly on the original value.
Using the Select Spoke statement (switch case) is better than using multiple if,else if statements.
Use Var_dump to debug PHP code. If you're looking for PHP debugging technology, I have to say that var_dump should be the target you're looking for, and this command can meet all your needs in terms of displaying PHP information, and most of the debugging code is related to getting the values in PHP.
The full path is used when the file is included and less time is required to resolve the operating system path.
It's a bad idea to create global values at every turn, but sometimes the real thing really needs to be done. It's a good idea to use global values for database tables or database connection information, but don't use global values frequently in your PHP code. In addition, a better approach is to keep your global variables in a config.php file.
If you want to know when the script starts executing, using $_server[' request_time ' is better than time ().
Open the Apache mod_deflate module.
Using the @ Mask error message is very inefficient.
Try to use a lot of PHP built-in functions.
Incrementing an undefined local variable is 9 to 10 times times slower than incrementing a predefined local variable.
A method in a derived class runs faster than the same method defined in the base class.
Defining only a local variable without calling it in a function also slows down (the level of the equivalent increments a local variable)
Apache parses a PHP script 2 to 10 times times slower than parsing a static HTML page. Use static HTML pages as much as possible and use less scripting.
As mentioned earlier, 99% of the most important parts of any PHP site are probably databases. Therefore, you need to be very familiar with how to use SQL correctly, learn relational tables, and more advanced database technologies.
Calls an empty function with one parameter, which takes as much time as 7 to 8 increments of local variables.
When you manipulate strings and need to verify that their lengths meet certain requirements, you will of course use the strlen () function. This function executes fairly quickly because it does not do any calculations and returns only the known string lengths stored in the Zval structure (c's built-in data structure for storing PHP variables).
Not all situations must use object-oriented development, and object-oriented is often expensive, and each method and object invocation consumes a lot of memory.
Unless the script can be cached, it will be recompiled every time it is invoked. The introduction of a set of PHP caching mechanisms typically increases performance from 25% to 100% to exempt compilation overhead.

1. If you can use file_get_contents instead of file, fopen, feof, Fgets and other series of methods, as far as possible with file_get_contents, because his efficiency is much higher! But pay attention to file_get_ Contents PHP version problem when opening a URL file;
2. As little as possible file operation, although the PHP file operation efficiency is not low;
3. Optimize select SQL statements, as little as possible in the case of INSERT, update operations (on the update, I was a bad batch);
4. Use PHP internal function as much as possible (but I have to find a function that does not exist in PHP, wasting the time that can write a custom function, experience problem ah!);
5. Do not declare variables inside the loop, especially large variables: objects (this seems to be not just a matter of note in PHP?);
6. Multidimensional arrays as far as possible not to cycle nested assignment;
7. Do not use regular expressions when you can use PHP internal string manipulation functions;
8.foreach more efficient, try to use foreach instead of while and for loops;
9. Use single quotes instead of double quotes to quote strings;
10. Replace I=i 1 with i = 1. In accordance with the habit of carbon C, efficiency is also high ";
11. For global variables, you should unset () out
12. In multiple nested loops, if possible, the longest loop should be placed in the inner layer, with the shortest loop being placed on the outside, which can reduce the number of times the CPU cuts across the loop layer, thereby optimizing program performance.
53 Details of PHP code optimization

1, if you can define the method of the class as static, as far as possible to define static, it will increase the speed of nearly 4 times times.
2, $row [' ID '] speed is $row[id] 7 times times.
3, ECHO is faster than print, and uses Echo's multiple arguments (to refer to a comma rather than a period) instead of a string connection, such as Echo $str 1, $str 2.
4, before executing the For loop to determine the maximum number of loops, do not calculate the maximum value per cycle, preferably using foreach instead.
5, the cancellation of those unused variables, especially large arrays, in order to free memory.
6, try to avoid the use of __get,__set,__autoload.
7, require_once () costly.
8, include files as far as possible using the absolute path, because it avoids the PHP to include_path to find the file speed, parsing the operating system path requires less time.
9, if you want to know the script to start execution (that is, the server to receive client requests) at the moment, using $_server[' request_time ' is better than time ().
10. Functions do the same function instead of regular expressions.
11, the Str_replace function is faster than the Preg_replace function, but the efficiency of the STRTR function is four times times that of 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, consider writing an extra paragraph of substitution code so that each pass parameter is a character, rather than writing a single line of code to accept the array as a query and replacement parameter.
13. Using the Select Branch statement (switch case) is better than using multiple if,else if statements.
14, using the @ block error message is very inefficient, extremely inefficient.
15, open the Apache mod_deflate module, you can improve the browsing speed of the Web page.
16, the database connection should be turned off when use is finished, do not use long connection.
17. Error messages are costly.
18, in the method to increase the local variable, speed is the fastest. Almost as fast as calling a local variable in a 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 predefined local variable.
22. Defining only one local variable instead of calling it in a function also slows down the speed (which is equivalent to incrementing a local variable). PHP will probably check to see if there are any global variables.
23. The method call appears to have nothing to do with the number of methods defined in the class, because I added 10 methods (both before and after the test method), but there was no change in performance.
24. Methods in a derived class run faster than the same method defined in the base class.
25. Call an empty function with one parameter, which takes as much time as 7 to 8 local variable increment operations. A similar method invocation takes approximately 15 times of local variable increments.
26, the time of Apache parsing a PHP script is 2 to 10 times times slower than parsing a static HTML page. Use static HTML pages as much as possible and use less scripting.
27. Unless the script can be cached, it will be recompiled every time it is invoked. The introduction of a set of PHP caching mechanisms typically increases performance from 25% to 100% to exempt compilation overhead.
28, try to do the cache, you can use memcached. Memcached is a high-performance memory object caching system that can be used to speed up dynamic Web applications and reduce database load. It is useful to cache the operation Code (OP code) so that the script does not have to recompile for each request.
29. When manipulating strings and having to check whether their lengths meet certain requirements, you will of course use the strlen () function. This function executes fairly quickly because it does not do any calculations and returns only the known string lengths stored in the Zval structure (c's built-in data structure for storing PHP variables). However, since strlen () is a function, it will be somewhat slower, because function calls go through a number of steps, such as lowercase letters, PHP is case-insensitive, and hash lookups follow the functions that are called. In some cases, you can use the isset () technique to speed up the execution of your code.
(Examples 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 lookup and lowercase. That is, you're actually not spending too much on the top-level code that verifies the length of the string.
34, when the execution variable $i increment or decrement, $i + + will be slower than the + + $i. This difference is specific to PHP and does not apply to other languages, so please do not modify your C or Java code and expect them to quickly become useless. + + $i faster because it requires only 3 instructions (opcodes), $i + + requires 4 instructions. A post increment actually produces a temporary variable, which is then incremented. And the predecessor increment increases directly on the original value. This is one of the most optimized processes, as Zend's PHP optimizer has done. Keeping this optimization in mind is a good idea, because not all command optimizer will do the same optimization, and there are a large number of Internet service providers (ISPs) and servers that do not have assembly instruction optimizer.
35, is not a matter of object-oriented (OOP), object-oriented often expensive, each method and object calls will consume a lot of memory.
36, not to use the class to implement all the data structure, the array is also useful.
37, do not subdivide the method too much, carefully think about what you really intend to reuse the code?
38, when you need, you can always break down the code into a method.
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 can consider using C extensions to implement them.
41, evaluate the test (profile) your code. The inspector will tell you which parts of the code are consuming much of the time. The Xdebug debugger includes a test procedure that can be used to show code bottlenecks in general.
42, Mod_zip can be used as Apache module, to instantly compress your data, and to reduce the amount of data transfer by 80%.
43, can use file_get_contents instead of file, fopen, feof, Fgets, and other series of methods, as far as possible with file_get_contents, because his efficiency is much higher! But pay attention to file_get_contents in opening a URL file when the PHP version problem;
44, as far as possible the file operation, although the PHP file operation efficiency is not low;
45, optimize the Select SQL statements, as far as possible, as little as possible insert, update operation (in update, I was a bad batch);
46, as far as possible use of PHP internal functions (but I was in order to find a PHP does not exist in the function, wasted the time to write a custom function, experience problems AH!) );
47. Do not declare variables inside the loop, especially large variables: objects (this seems to be not just a matter of note in PHP)? );
48, multidimensional array as far as possible not to cycle nested assignment;
49, in the case of PHP internal string manipulation function, do not use regular expression;
50, foreach more efficient, as far as possible with foreach instead while and for loops;
51, the use of single quotes instead of double quotes quoted strings;
52, "Replace I=i+1 with I+=1." In line with C + + habits, efficiency is also high ";
53, to global variables, should be used up on the unset () off;

Finally, summarize the common and important PHP optimization strategies:

First, use absolute paths in includes and requires, which takes less time to parse paths;
Two, do not use functions in the loop, such as for ($x =0; $x < count ($array); $x), the count () function is evaluated out first;
Third, 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. But if you're using a shared virtual host, php.ini you can't modify, then you'd better add the error_reporting (0) function, put 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;
Four, prevent too many loops, nested too many loops will pull down the execution efficiency
v. Prohibit the execution of the relevant query statements within the loop, unless you do not, you must not do so.
Six, try to use single quotation marks to join the string
Seven, as much as possible to reduce the copy operation of the variable. For example: $description = $_post[' description '];
Eight, when if/else too much, use switch/case instead of if/else as much as possible. Can make code more concise
Nine, open caching mechanism to help improve performance, while reducing MySQL load
10, turn on gzip compression

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: info-contact@alibabacloud.com 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.