Steps for optimizing the PHP program)

Source: Internet
Author: User
Tags switch case
Methods to optimize the PHP program (learn more) 1. Ifamethodc ++ anbestatic, declareitstatic. Speedimprovementisbyafactorof4. if a method can be static, make a static statement on it. The speed can be increased to 4 times. 2. echoisfasterthanprint. echo method for optimizing PHP programs than pri)

1. If a method c ++ an be static, declare it static. Speed improvement is by a factor of 4. If a method can be static, make a static declaration on it. The speed can be increased to 4 times.

2. echo is faster than print. echo is faster than print.

3. Use echo's multiple parameters instead of string concatenation. Use multiple parameters of echo to replace string connections with commas instead of periods.

4. Set the maxvalue for your for-loops before and not in the loop. determine the maximum number of cycles before executing the for loop. do not calculate the maximum value for each loop.

5. Unset your variables to free memory, especially large arrays. cancel unnecessary variables, especially large arrays, to release the memory.

6. Avoid magic like _ get, _ set, _ autoload Avoid using _ get ,__ set ,__ autoload.

7. require_once () is expensive.

8. Use full paths in between DES and requires, less time spent on resolving the OS paths. Use the full path when the file is included, and less time is required to parse the operating system path.

9. if you need to find out the time when the script started executing, $ _ SERVER ['request _ time'] is preferred to TIME () If you want to know how to execute the script: that is, when the SERVER receives a client REQUEST, the use of $ _ SERVER ['request _ time'] is better than the TIME ().

10. See if you can use strncasecmp, strpbrk and stripos instead of regex. check whether strncasecmp, strpbrk, and stripos functions can be used in place of regular expressions to complete the same function.

11. str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4. 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.

12. if the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments. 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 row The code accepts arrays as query and replacement parameters.

13. It's better to use select statements than multi if, else if, statements. Using the select branch statement (: switch case) is better than using multiple if and else if statements.

14. Error suppression with @ is very slow. [email protected]

15. Turn on apache's mod_deflate to open apache's mod_deflate module.

16. Close your database connections when you're done with them. the database connection should be closed after use.

17. $ row ['id'] is 7 times faster than $ row [id]. $ row ['id'] is 7 times more efficient than $ row [id.

18. Error messages are expensive. the Error message is expensive.

19. do not use functions inside of for loop, such as for ($ x = 0; $ x <count ($ array); $ x) The count () function gets called each time. do not use functions in a for loop, such as for ($ x = 0; $ x <count ($ array); $ x). the count () function is called once every loop.

20. Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function. incremental local variables in the method are the fastest speed. It is almost the same as calling a local variable in a function.

21. Incrementing a global variable is 2 times slow than a local var. increasing a global variable is twice slower than increasing a local variable.

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

23. incrementing an undefined local variable is 9-10 times slower than a pre-initialized one. increasing an unspecified local variable is 9 to 10 times slower than increasing a predefined local variable.

24. Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var ). PHP probably does a check to see if the global exists. defining only one local variable without calling it in the function also slows down (to the extent that it is equivalent to increasing one local variable ). PHP will probably check whether global variables exist.

25. method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance. 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.

26. Methods in derived classes run faster than ones defined in the base class. the Methods in the derived class run faster than the same Methods defined in the base class.

27. A function call with one parameter and an empty function body takes about the same time as doing 7-8 $ localvar ++ operations. A similar method call is of course about 15 $ localvar ++ operations. calling an empty function with a parameter takes seven to eight times to increase the number of local variables. Similar method calls take nearly 15 times to increment local variables.

28. Surrounding your string by 'instead of "will make things interpret a little faster since php looks for variables inside "... "But not inside '... '. Of course you can only do this when you don't need to have variables in the string. use single quotes instead Of double quotes to include strings, which is faster. Because PHP searches for variables in strings enclosed by double quotation marks, but not in single quotes. Of course, this can be done only when you do not need to include the variable in the string.

29. when echoing strings it's faster to separate them by comma instead of dot. note: This only works with echo, which is a function that can take several strings as arguments. when multiple strings are output, use commas instead of periods to separate strings, which is faster. Note: Only echo can do this. it is a "function" that treats multiple strings as parameters. echo is a language structure rather than a real function, so the function is added with double quotation marks ).

30. a php script will be served at least 2-10 times slower than a static HTML page by Apache. try to use more static HTML pages and fewer scripts. 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.

31. your PHP scripts are recompiled every time unless the scripts are cached. install a PHP caching product to typically increase performance by 25-100% by removing compile times. 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.

32. cache as much as possible. use memcached-memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load. OP code caches are useful so that your script does not have to be compiled on every request. use memcached. 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.

33. when working with strings and you need to check that the string is either of a certain length you 'd understandably wowould want to use the strlen () function. this function is pretty quick since it's operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP ). However because strlen () is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. in some instance you can improve the speed of your code by using an isset () trick. 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.

Ex. (for example)

If (strlen ($ foo) <5) {echo "Foo is too short ";}

Vs. (compared with the following tips)

If (! Isset ($ foo {5}) {echo "Foo is too short ";}

Calling isset () happens to be faster then strlen () because unlike strlen (), isset () is a language construct and not a function meaning that it's execution does not require function lookups and lowercase. this means you have always ally no overhead on top of the actual code that determines the string's length. 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 overhead in the top-level code that checks the string length.

34. 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 t He creation of a temporary var that is then incremented. while pre-incrementation increases the original value directly. this is one of the optimization that opcode optimized like Zend's PHP optimizer. it is 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 ++ compares with + + $ I is slower. This difference is exclusive to PHP and does not apply to other languages. therefore, do not modify your C or Java code and expect it 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 the post-increment mode, and the temporary variable 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.

35. not everything has to be OOP, often it is too much overhead, each method and object call consumes a of lot memory. it is not essential for object-oriented (OOP). object-oriented usually has a high overhead, and each method and object call consumes a lot of memory.

36. Do not implement every data structure as a class, arrays are useful, too. arrays are also useful instead of using classes to implement all data structures.

37. Don't split methods too much, think, and which code you will really re-use. Don't subdivide the methods too much. think carefully about what code you actually intend to reuse?

38. You can always split the code of a method later, when needed. when You need it, You can always break down the code into methods.

39. Make use of the countless predefined functions. try to use a large number of PHP built-in functions.

40. if you have very time consuming functions in your code, consider writing them as C extensions. if a large number of time-consuming functions exist in the code, you can consider using C extension to implement them.

41. profile your code. A profiler shows you, which parts of your code consumes how much time. the Xdebug debugger already contains a profiler. profiling shows you the bottlenecks in overview. 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.

42. mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80%. mod_zip can be used as an Apache module to instantly compress your data and reduce the data transmission volume by 80%.

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