Home > Backend Development > PHP Tutorial > Recommendations for optimizing PHP code_PHP Tutorial

Recommendations for optimizing PHP code_PHP Tutorial

WBOY
Release: 2016-07-21 14:52:24
Original
761 people have browsed it

1. If a method can be static, declare it static. Speed ​​improvement is by a factor of 4. If a method can be static, declare it static. 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 echo’s multiple parameters instead of string concatenation.

4. Set the maxvalue for your for-loops before and not in the loop. Determine the maximum number of loops before executing the for-loop, and do not calculate the maximum value every time you loop.

5. Unset your variables to free memory, especially large arrays. Unset your variables to free memory, especially large arrays.

6. Avoid magic like __get, __set, __autoload Try to avoid using __get, __set, __autoload.

7. require_once() is expensive require_once() is expensive.

8. Use full paths in includes and requires, less time spent on resolving the OS paths.

9. If you need to find out the time when the script started executing, $_SERVER['REQUEST_TIME'] is preferred to time() ), it is better to use $_SERVER['REQUEST_TIME'] than time().

10. See if you can use strncasecmp, strpbrk and stripos instead of regex. Check whether you can use strncasecmp, strpbrk and stripos functions instead 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. str_replace function is faster than preg_replace function, but strtr function is four times more efficient than 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 accepts arrays or characters as parameters, and the parameter length is not too long, then you can consider writing an additional replacement code so that the parameters are passed each time is a character instead of just writing a line of code that accepts arrays as parameters for query and replace.

13. It’s better to use select statements than multi if, else if, statements.

14. Error suppression with @ is very slow. Using @ to block error messages is very inefficient.

15. Turn on apache’s mod_deflate Turn on apache’s mod_deflate module.

16. Close your database connections when you’re done with them.

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. Error messages are 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. Try not to use functions inside for Functions are used in loops, such as for ($x=0; $x < count($array); $x), which calls the count() function every time it loops.

20. Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function. Incrementing a local variable in a method is the fastest. Almost as fast as calling local variables in a function.

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

22. Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable. Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable. times.

23. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one. Incrementing an undefined local variable is 9 to 10 times slower than a pre-initialized one.

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. Calling it without a function will also slow things down (to the same extent as incrementing a local variable). PHP will probably check to see if a global variable exists.

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. The number of methods defined in has nothing to do with it, since I added 10 methods (both before and after the test method) but there was no change in performance.

26. Methods in derived classes run faster than ones defined in the base class. Methods in derived classes 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. function, the time it takes is equivalent to performing 7 to 8 local variable increment operations. A similar method call takes close to 15 local variable increment operations.

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. Wrapping the string in single quotes instead of double quotes is faster because PHP will search for variables in a string enclosed in double quotes, but not in single quotes. Of course, only if you don't. This can only be done if you need to include variables 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 outputting multiple strings, use comma instead of period. to separate strings, which is faster. Note: Only echo can do this. It is a "function" that can take multiple strings as parameters (Annotation: The PHP manual says that echo is a language structure, not a real function, so the function is enclosed in double quotes. ).

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. Pages are 2 to 10 times slower. Try to use more static HTML pages and less scripts.

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. once. Introducing a PHP caching mechanism can usually improve performance by 25% to 100% to eliminate 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. Try to cache as much as possible, you can use memcached. Memcached is a high-performance memory object caching system that can be used to accelerate dynamic web applications and reduce database load. Caching of OP codes is useful so that scripts do not have to be recompiled for each request.

33. When working with strings and you need to check that the string is either of a certain length you'd understandably would 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 a string and need to check whether its length meets certain requirements, you will naturally Use strlen() function. This function executes quite quickly because it does not do any calculations and just returns the known length of the string stored in the zval structure (C's built-in data structure used to store PHP variables). However, since strlen() is a function, it will be somewhat slow, because the function call will go through many steps, such as lowercase letters (Annotation: refers to the lowercase function name, PHP does not distinguish between uppercase and lowercase function names), hash search, Will be executed together with the called function. In some cases, you can use the isset() trick to speed up the execution of your code.

Ex. (example below)

if (strlen($foo) < 5) { echo "Foo is too short"; }
vs. (Compare with the tips below)
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 virtually 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(), as a language construct, means that its execution does not require a function lookup. and lowercase letters. That is, you actually don't spend much overhead in the top-level code that checks the length of the string.

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 languages, 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 the 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 performing increment or decrement of variable $i, $i++ will be slower than ++$i. This difference is specific to PHP and does not apply to other languages, so please don't modify your C or Java code and expect it to be instantly faster, it won't work. ++$i is faster because it only requires 3 instructions (opcodes), while $i++ requires 4 instructions. Post-increment actually creates a temporary variable that is subsequently incremented. Prefix increment increases directly on the original value. This is a form of optimization, as done by Zend's PHP optimizer. It's a good idea to keep this optimization in mind because not all command optimizers perform the same optimizations, and there are a large number of Internet Service Providers (ISPs) and servers that do not have command optimizers installed.

35. Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory. and object calls will consume a lot of memory.

36. Do not implement every data structure as a class, arrays are useful, too. Do not implement every data structure as a class, arrays are useful, too.

37. Don’t split methods too much, think, which code you will really re-use. Don’t split methods too much, think, which code you will really re-use.

38. You can always split the code of a method later, when needed. When you need, you can always split 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.

41. Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview. Profile your code. The checker will tell you which parts of the code take how much time. The Xdebug debugger includes inspection programs that evaluate the overall integrity of your code and reveal bottlenecks in your code.

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_gzip can be used as an Apache module to instantly compress your data and can reduce the data transfer up to 80%. Volume is reduced by 80%.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/371576.htmlTechArticle1. If a method can be static, declare it static. Speed ​​improvement is by a factor of 4. If a If a method can be made static, just declare it statically. The speed can be increased to 4 times. 2. ech...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template