1. Try to be static:
If a method can be static, it is declared static, the speed can be increased by 1/4, even when I test, this improved by nearly three times times.
Of course, this test method needs to be executed at level 100,000 and above, the effect is obvious.
In fact, the efficiency of static and non-static methods are mainly different in memory: Static method to generate memory at the beginning of the program, the instance method in the program run to generate memory, so the static method can be called directly, the instance method to first genetic instance, through the instance call method, the static speed is very fast, but more will account for memory.
Any language is the operation of memory and disk, as to whether object-oriented, only the software layer of the problem, the bottom is the same, but the implementation method is different. Static memory is continuous, because it is generated at the beginning of the program, and the instance is requesting a discrete space, so of course there is no static method fast.
Static methods always call the same piece of memory, the disadvantage is that it cannot be destroyed automatically, but the instantiation can be destroyed.
2.echo is more efficient than print, because Echo has no return value, and print returns an integer type;
Test:
Echo
0.000929-0.001255 s (average 0.001092 seconds)
Print
0.000980-0.001396 seconds (average 0.001188 seconds)
A difference of about 8%, the overall echo is relatively fast.
Note that when the echo is large, the performance is severely affected if no adjustment is made. Use the mod_deflate that opens apached to compress or open Ob_start first to put the content into the buffer.
3. Set the maximum number of cycles before the loop, not in the loop;
Fools all understand the truth.
4. Destroy the variable to release the memory, especially the large array;
Arrays and objects in PHP are particularly memory-caused by PHP's underlying Zend engine,
In general, the memory utilization of the PHP array is only 1/10, that is, a C language inside the 100M memory array, in PHP 1G is necessary.
In particular, in the system of PHP as a background server, there are often problems with memory costs too much.
5. Avoid using magic methods like __get, __set, __autoload, etc.;
The functions that begin with __ are named Magic Functions, which are first visited under certain conditions. In a sense, there are several magic functions
__construct (), __destruct (), __get (), __set (), __unset (), __call (), __callstatic (), __sleep (), __wakeup (), __tostring () , __set_state (), __clone (), __autoload ()
In fact, if __autoload does not efficiently match the class name to the actual disk file (note that this refers to the actual disk file, not just the file name), the system will have to do a large number of files exist (need to be found in each include path to find) judgment, It is well known that disk I/O operations are inefficient in determining if a file exists, so this is why the autoload mechanism is less efficient.
Therefore, when designing a system, we need to define a clear set of mechanisms for mapping the class name to the actual disk file. The simpler and clearer the rule, the higher the efficiency of the autoload mechanism.
Conclusion: The autoload mechanism is not a natural inefficiency, only the misuse of AutoLoad, the design of a bad automatic loading function will lead to the reduction of its efficiency.
So it is debatable to avoid using __autoload magic method as far as possible.
6.requiere_once () comparative consumption of resources;
This is because requiere_once needs to determine if the file has been referenced, so it can not be used as much as possible. Commonly used require/include methods to avoid.
7. Use absolute paths in includes and requires.
If you include a relative path, PHP will traverse the include_path to find the file.
This type of problem is avoided with absolute paths, so less time is required to resolve the operating system path.
8. $_server[' Requset_time ' is better than time () if you need to get the script to execute.
Can imagine. One is ready to use directly, and one needs the result of the function.
9. If you can use PHP internal string manipulation functions, try to use them, do not use regular expressions, because their efficiency is higher than the regular;
Not to say, the most consumption of performance.
Is there a useful function you missed? For example: Strpbrk () strncasecmp () Strpos ()/strrpos ()/stripos ()/strripos () acceleration STRTR If you need to convert all of a single character,
Use strings instead of arrays to do STRTR:
<?php
$ADDR = STRTR ($addr, "ABCD", "efgh"); Good
$ADDR = STRTR ($addr, Array (' a ' = = ' E ',)); Bad
?>
Efficiency improvement: 10 times times.
10.str_replace character substitution singular replace preg_replace fast, but STRTR is 1/4 faster than str_replace;
And don't make unnecessary replacements. Str_replace also allocates memory for its parameters, even if there is no replacement. Very slow! Workaround:
Use Strpos to find first (very fast), see if there is a need to replace, if necessary, replace efficiency:-If need to replace: efficiency is almost equal, the difference is about 0.1%.
If you do not need to replace: Use Strpos fast 200%.
11. The parameter is a string
If a function can accept both an array and a simple character as a parameter, such as a character substitution function, and the argument list is not too long, consider writing an additional replacement code so that each pass argument is a character, rather than accepting the array as a find and replace parameter. Punches,1+1>2;
12. It is best not to use @ to cover up the error will slow down the script run;
With @ Actually there are 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.
$row [' id '] 7 times times faster than $row[id]
It is suggested that the habit of adding quotation marks to array keys;
14. Do not use functions in the loop
For example, for ($x =0; $x < count ($array); $x), the count () function is calculated outside the first; you know why.
16. The fastest way to create local variables in a class method is almost as fast as calling local variables in a method; 17. Building a global variable is twice times slower than local variables;
Because the local variables are in the stack, when a function occupies a stack space is not very large, this part of the memory is likely to hit the cache, this time the CPU access efficiency is very high.
Conversely, if a function uses both a global variable and a local variable, the CPU cache needs to switch back and forth when the two addresses are large, and then the efficiency drops.
(I understand.)
18. Create an object property (a variable inside a class) for example ($this->prop++) is 3 times times slower than a local variable; 19. Creating an undeclared local variable is 9-10 times slower than an already defined local variable by 20. Declaring a global variable that is not used by any of the functions also degrades performance (as well as declaring the same number of local variables).
PHP may go to check if this global variable exists;
21. The performance of the method is not related to the number of methods defined within a class
Because I add 10 or more methods to the test class (these methods before and after the test method) performance is no different;
22. The performance of the method in the subclass is better than in the base class; 23. Only one parameter is called and the function that is empty is equal to 7-8 $localvar++ operation, and a similar method (function in class) runs equal to about 15 times $localvar++ operation; 24 Using single quotes instead of double quotation marks to contain strings can be faster.
Because PHP searches for a variable in a string surrounded by double quotes, the single quotation mark does not.
The PHP engine allows the use of single and double quotes to encapsulate string variables, but this is a big difference! A string using double quotes tells the PHP engine to first read the string contents, look for the variable in it, and change the value to the variable. Generally speaking, strings are not variable, so using double quotes can cause poor performance. It is best to use the word
String concatenated instead of double-quoted strings.
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. Use commas instead of point connectors when echo strings are faster.
Echo is a "function" that can take multiple strings as arguments: The PHP manual says that ECHO is a language structure, not a real function, so add a double quote to the function.
For example, Echo $str 1, $str 2.
26.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 fewer scripts.
28. Use the cache as much as possible, and suggest using memcached.
High-performance distributed memory object cache system, improve the performance of dynamic network applications, reduce the burden of the database;
It is also useful for caching Code (OP code) so that the script does not have to recompile for each request.
29. Use the Ip2long () and LONG2IP () functions to convert the IP address into an integer type into the database instead of the character type.
This reduces storage space by almost 1/4. At the same time, the address can be easily sorted and quickly find;
30. Use CHECKDNSRR () to confirm the validity of some email addresses through the presence of a domain name
This built-in function ensures that each domain name corresponds to an IP address;
31. Use Mysql_* 's improved function mysqli_*;32. Try to prefer the ternary operator (?:); 33. Whether you need to pear
Before you want to completely re-do your project, see if Pear has anything you need. Pear is a huge repository of resources that many PHP developers know;
35. 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 can effectively protect sensitive SQL queries and paths from being displayed when errors occur;
36. Use Gzcompress () and gzuncompress () to compress (decompress) the large-capacity string when the database is stored in (out).
This built-in function can be compressed to 90% using the GZIP algorithm;
37. Make a function have multiple return values by referring to the argument variable address.
You can add a "&" to the variable before it is passed by address rather than by value;
38. Fully understand the dangers of magic referencing and SQL injection.
Fully Understand "magic quotes" and the dangers of SQL injection. I ' m hoping that most developers reading this is 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. Some places use isset instead of strlen
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.
40. Use + + $i increment
When incrementing or decrementing the value of the variable $i + + happens to bes a tad slower then + + $i. This is something PHP specific and does don't apply to other languages, so don ' t go modifying your C or Java code thinking I T ' ll suddenly become faster, it won ' t. + + $i happens to being 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's then incremented. While preincrementation increases the original value directly. This is one of the optimization so opcode optimized like Zend ' s PHP optimizer. It's a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty O F ISPs and servers running without an opcode optimizer.
When the variable $i is incremented or decremented, $i + + will be slower $i than the + +. 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's a good idea to keep this optimization in mind, because not all of the instruction optimizer will do the same optimizations, and there are a lot of internet services that don't have an assembly instruction optimizer
Providers (ISPs) and servers.
40. 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 '];
41 using the Select Branch statement
The switch case is better than using multiple if,else if statements, and the code is easier to read and maintain.
42. File_get_contents can be substituted for file, fopen, feof, fgets
In the case can be replaced with file_get_contents 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;
43. As much as possible file operation, although PHP file operation efficiency is not low; 44. Optimize the Select SQL statement to make the insert and update operations as few as possible (on update, I have been bad) ; 45. Use PHP intrinsics as much as possible 46. Do not declare variables inside the loop, especially large variables: objects
(This is not just a question to be aware of in PHP, is it?) );
47. Multi-dimensional array try not to loop nested assignment, 48.foreach is more efficient, try to use foreach instead of while and for loop; 49. " Replace i=i+1 with I+=1. In line with the custom of C + +, the efficiency is high "; 50. The global variable should be unset () off; 51 is not a matter of object-oriented (OOP), object-oriented is often expensive, and each method and object invocation consumes a lot of memory. 52 don't subdivide the method too much, think about what code you really want to reuse? 53 If there are a lot of time-consuming functions in your code, you might consider implementing them in C extensions. 54, open the Apache mod_deflate module, can improve the browsing speed of the page.
(mention of the echo big variable problem)
55, the database connection should be turned off when used, do not use long connection. 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.
Pick From: http://www.cnblogs.com/glory-jzx/archive/2012/08/21/2649712.html
PHP High-efficiency notation