Sharing 50 tips for improving PHP Execution efficiency _ php instances

Source: Internet
Author: User
This article mainly introduces 50 tips for improving PHP Execution efficiency. For more information, see 1. Use single quotes instead of double quotation marks 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 ).

2. 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.

3. $ row ['id'] is 7 times faster than $ row [id.

4. echo is faster than print, and multiple echo parameters are used to replace string connections, such as echo $ str1, $ str2.

5. determine the maximum number of cycles before executing the for loop. Do not calculate the maximum value for each loop. Use foreach instead.

6. Cancel unnecessary variables, especially large arrays, to release the memory.

7. Avoid using _ get ,__ set ,__ autoload whenever possible.

8. require_once () is expensive.

9. Try to use the absolute path when you include the file, because it avoids the speed for PHP to search for the file in include_path, and it takes less time to parse the operating system path.

10. Use
$ _ SERVER ['request _ time'] is better than TIME ()

11. functions use the same function instead of regular expressions.

12. 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.

13. 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.

14. Using the select branch statement is better than using multiple if and else if statements.

15. Blocking error messages with @ is very inefficient and extremely inefficient.

16. Open the mod_deflate module of apache to speed up web page browsing.

17. The database connection should be closed when use is complete. Do not use persistent connections.

18. The error message is expensive.

19. Increment local variables in the method at the fastest speed. It is almost the same as calling a local variable in a function.

20. Increasing a global variable is twice slower than increasing a local variable.

21. Incrementing an object property (for example, $ this-> prop ++) is three times slower than incrementing a local variable.

22. Increasing an unspecified local variable is 9 to 10 times slower than increasing a predefined local variable.

23. 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.

24. 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.

25. The method in the derived class runs faster than the same method defined in the base class.

26. 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.

27. 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. 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.

29. 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.

30. 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 (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 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)

The Code is as follows:


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.

31. 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.

32. it is not essential for Object-Oriented (OOP). Object-oriented usually has a high overhead, and every method and object call consumes a lot of memory.

33. arrays are also useful instead of using classes to implement all data structures.

34. Do not subdivide the methods too much. Think carefully about the code you actually intend to reuse?

35. when you need it, you can always break down the code into methods.

36. Try to use a large number of PHP built-in functions.

37. If there are a large number of time-consuming functions in the code, you can consider using C extension to implement them.

38. 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.

39. mod_zip can be used as an Apache module to instantly compress your data and reduce the data transmission volume by 80%.

40. 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;

41. Perform as few file operations as possible, although PHP file operations are not efficient;

42. Optimize Select SQL statements and perform Insert and Update operations as little as possible (I have been maliciously approved in update );

43. 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 a problem of experience !);

44. Do not declare variables inside the loop, especially big variables: Objects (doesn't it seem to be a concern in PHP ?);

45. Do not use nested values for multi-dimensional arrays;

46. Do not use regular expressions when using internal PHP Strings To operate functions;

47. foreach is more efficient. Use foreach instead of the while and for loops;

48. Use single quotes instead of double quotes to reference strings;

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. Use checkdnsrr () to confirm the validity of some email addresses through the existence of domain names. This built-in function can ensure that each domain name corresponds to an IP address;

52. If you are using php5 and mysql4.1 or later versions, consider using the mysql _ improved function mysqli _;

53. Use highlight_file () to automatically print a copy of the Well-formatted page source code;

54. 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;

55. 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;

56. 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;

57. Disable the Magic Quote function of PHP. Not every piece of escaped data needs to be inserted into the database. If all the data entering PHP is escaped, this will have a certain impact on the execution efficiency of the program. Calling escape functions (such as addslashes () at runtime is more efficient

58. 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;

59. 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;

60. 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.

61. Replacing strlen with isset 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 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" $} (compared 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.

I hope you will like the above 50 tips to improve PHP Execution efficiency.

Related Article

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.