PHP efficient writing and reasons

Source: Internet
Author: User
Tags switch case
1. Static Method as much as possible: if a method can be static, it should be declared as static. The speed can be improved by 14, or even improved 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 are generated at the beginning of the program

1. Static Method as much as possible: if a method can be static, it should be declared as static. 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 are generated at the beginning of the program

1. Static Method as much as possible: if a method can be static, it should be declared as static. 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. echo is more efficient than print. Because echo does not return a value, print returns an integer. Test: Echo 0.000929-0.001255 s (average 0.001092 seconds) Print 0.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, rather than in the loop. dummies understand the truth.

4. destroys variables to release memory, especially large arrays. arrays and objects occupy especially memory in php, which is caused by php's underlying zend engine. Generally, the memory usage of the PHP array is only 1/10, that is, an array of 100 MB memory in the 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. do not use magic methods such as _ get, _ set, and _ autoload. For functions starting with _, name them magic functions, such functions 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 () Actually, 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. 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. 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:

'E',); // bad?>

Efficiency Improvement: 10 times.

10. str_replace character replacement is faster than regular expression replacement preg_replace, but strtr is 1/4 faster than str_replace. In addition, do not replace str_replace the str_replace parameter to allocate memory even if it is not replaced. Very slow! Solution: Use strpos to search for it first (very fast) and check whether it needs to be replaced. If necessary, replace the efficiency:-If it needs to be replaced: the efficiency is almost the same, and the difference is 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, for example, 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 @ reduces the script running speed. In fact, there are 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. in a loop, do not use functions such as 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 large, this part of memory is likely to 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 the 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 difference in post-performance;

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 best to connect strings with character strings 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 '. $ 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 the database. It is also useful for OP code caching, the script does not need to be re-compiled for 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. Do you need PEAR? 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. ini You cannot modify, so you 'd better add the error_reporting (0) function and put it in the first line of each script file (or load it using require_once) this effectively protects sensitive SQL queries and paths from being displayed when an error occurs;

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. In some cases, use isset instead of strlen. When you operate a string and check 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" $} (compared with the following tips) if (! Isset ($ foo {5}) {echo "Foo is too short" $} call isset () happens to be faster than strlen (), because unlike the latter, as a language structure, isset () does not require function searches and lowercase letters 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. use ++ $ I to increase 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 cau Ses 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 service providers (ISPs) that do not have command optimizers) and server. 40. do not just copy variables. 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 It is better to use multiple if and else if statements to switch case using the branch statement, and the code is easier to read and maintain.

42. when file_get_contents can be used to replace file, fopen, feof, and fgets, file_get_contents can be used to replace file, fopen, feof, fgets, and other methods, file_get_contents should be used whenever possible, because of his 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 big variables: Objects (Doesn't this seem to be a concern 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 explode. 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.

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.