Home  >  Article  >  Backend Development  >  53 details and optimization strategies for PHP code optimization

53 details and optimization strategies for PHP code optimization

青灯夜游
青灯夜游forward
2020-04-25 09:21:402955browse

This article will introduce you to 53 details of PHP code optimization and common and important optimization strategies. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

53 details and optimization strategies for PHP code optimization

53 details of PHP code optimization, common and important PHP optimization strategies.

Use single quotes instead of double quotes to enclose the string, which is faster. Because PHP will search for variables in strings surrounded by double quotes, single quotes will not. Note: only echo can do this, it is a "function" that can take multiple strings as parameters (Annotation: PHP Manual It is said that echo is a language structure, not a real function, so the function is enclosed in double quotes).

1. If you can define a class method as static, try to define it as static, and its speed will increase by nearly 4 times.

2. The speed of $row['id'] is 7 times that of $row[id].

3. Echo is faster than print, and uses multiple parameters of echo (annotation: refers to using commas instead of periods) instead of string concatenation, such as echo $str1, $str2.

4. Determine the maximum number of loops before executing the for loop. Do not calculate the maximum value every loop. It is best to use foreach instead.

5. Unregister unused variables, especially large arrays, to free up memory.

6. Try to avoid using __get, __set, __autoload.

7. require_once() is expensive.

8. Try to use absolute paths when including files, because it avoids the speed of PHP searching for files in include_path, and the time required to parse the operating system path will be less.

9. If you want to know the time when the script starts executing (annotation: that is, the server receives the client request), it is better to use $_SERVER['REQUEST_TIME'] than time().

10. Functions replace regular expressions to complete the same function.

11. 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 a string replacement function accepts arrays or characters as parameters, and the parameter length is not too long, you can consider writing an additional replacement code so that each parameter passed is a character instead of Just write one line of code to accept arrays as parameters for query and replace.

13. It is better to use a selective branch statement (translation annotation: switch case) than to use multiple if, else if statements.

14. Using @ to block error messages is very inefficient, extremely inefficient.

15. Turn on the mod_deflate module of apache to improve the browsing speed of web pages.

16. The database connection should be closed when finished using it. Do not use long connections.

17. Error messages are expensive.

18. Increasing local variables in the method is the fastest. Almost as fast as calling local variables in a function.

19. Incrementing a global variable is 2 times slower than incrementing a local variable.

20. Incrementing an object property (such as: $this->prop) is 3 times slower than incrementing a local variable.

21. Incrementing an undefined local variable is 9 to 10 times slower than incrementing a predefined local variable.

22. Just defining a local variable without calling it in a function will also slow down the speed (to the same extent as incrementing a local variable). PHP will probably check to see if a global variable exists.

23. Method calls appear to have nothing to do with the number of methods defined in the class, because I added 10 methods (both before and after testing the method), but there was no change in performance.

24. Methods in derived classes run faster than the same methods defined in base classes.

25. Calling an empty function with one parameter takes time equivalent to performing 7 to 8 local variable increment operations. A similar method call takes close to 15 local variable increment operations.

26. The time it takes for Apache to parse a PHP script is 2 to 10 times slower than parsing a static HTML page. Try to use more static HTML pages and less scripts.

27. Unless the script can be cached, it will be recompiled every time it is called. Introducing a PHP caching mechanism can usually improve performance by 25% to 100% to eliminate compilation overhead.

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

29. When operating a string and need to check whether its length meets certain requirements, you will naturally use the strlen() function. This function executes quite quickly because it does not do any calculations and just returns the known string length 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.

(Examples are as follows)

if (strlen($foo) < 5) { echo “Foo is too short”$$ }

(Compare with the techniques below)

if (!isset($foo{5})) { echo “Foo is too short”$$ }

调用isset()恰巧比strlen()快,因为与后者不同的是,isset()作为一种语言结构,意味着它的执行不需要函数查找和字母小写化。也就是说,实际上在检验字符串长度的顶层代码中你没有花太多开销。

34、当执行变量$i的递增或递减时,$i++会比++$i慢一些。这种差异是PHP特有的,并不适用于其他语言,所以请不要修改你的C或Java 代码并指望它们能立即变快,没用的。++$i更快是因为它只需要3条指令(opcodes),$i++则需要4条指令。后置递增实际上会产生一个临时变量,这个临时变量随后被递增。而前置递增直接在原值上递增。这是最优化处理的一种,正如Zend的PHP优化器所作的那样。牢记这个优化处理不失为一个好主意,因为并不是所有的指令优化器都会做同样的优化处理,并且存在大量没有装配指令优化器的互联网服务提供商(ISPs)和服务器。

35、并不是事必面向对象(OOP),面向对象往往开销很大,每个方法和对象调用都会消耗很多内存。

36、并非要用类实现所有的数据结构,数组也很有用。

37、不要把方法细分得过多,仔细想想你真正打算重用的是哪些代码?

38、当你需要时,你总能把代码分解成方法。

39、尽量采用大量的PHP内置函数。

40、如果在代码中存在大量耗时的函数,你可以考虑用C扩展的方式实现它们。

41、评估检验(profile)你的代码。检验器会告诉你,代码的哪些部分消耗了多少时间。Xdebug调试器包含了检验程序,评估检验总体上可以显示出代码的瓶颈。

42、mod_zip可作为Apache模块,用来即时压缩你的数据,并可让数据传输量降低80%。

43、在可以用file_get_contents替代file、fopen、feof、fgets等系列方法的情况下,尽量用 file_get_contents,因为他的效率高得多!但是要注意file_get_contents在打开一个URL文件时候的PHP版本问题;

44、尽量的少进行文件操作,虽然PHP的文件操作效率也不低的;

45、优化Select SQL语句,在可能的情况下尽量少的进行Insert、Update操作(在update上,我被恶批过);

46、尽可能的使用PHP内部函数(但是我却为了找个PHP里面不存在的函数,浪费了本可以写出一个自定义函数的时间,经验问题啊!);

47、循环内部不要声明变量,尤其是大变量:对象(这好像不只是PHP里面要注意的问题吧?);

48、多维数组尽量不要循环嵌套赋值;

49、在可以用PHP内部字符串操作函数的情况下,不要用正则表达式;

50、foreach效率更高,尽量用foreach代替while和for循环;

51、用单引号替代双引号引用字符串;

52、“用i+=1代替i=i+1。符合c/c++的习惯,效率还高”;

53、对global变量,应该用完就unset()掉;

最后,总结一下常见而重要的php优化策略:

一、 在includes和requires中使用绝对路径,这样在分析路径花的时间更少;

二、 在循环里别用函数,例如For($x=0; $x < count($array); $x),count()函数在外面先计算;

三、 使用error_reporting(0)函数来预防潜在的敏感信息显示给用户。理想的错误报告应该被完全禁用在php.ini文件里。可是如果你在用一个共享的虚拟主机,php.ini你不能修改,那么你最好添加error_reporting(0)函数,放在每个脚本文件的第一行(或用require_once()来加载)这能有效的保护敏感的SQL查询和路径在出错时不被显示;

四、 禁止过多的循环套循环,嵌套过多的循环会拉低执行效率

五、 禁止在循环内部执行相关的查询语句,除非万不得以,不然千万不可这么操作

六、 尽量使用单引号联接字符串

七、 尽可能的减少变量复制操作。例如:$description = $_POST['description'];

八、 当if/else过多时,尽可能的使用switch/case 代替 if/else。能够使代码更加简明

九、 开启缓存机制有助于提升性能,同时降低MySQL负载

十、 开启gzip压缩

更多相关知识,请关注 PHP中文网!!

The above is the detailed content of 53 details and optimization strategies for PHP code optimization. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete