Home  >  Article  >  Backend Development  >  How to optimize php code?

How to optimize php code?

青灯夜游
青灯夜游Original
2019-10-11 14:27:523994browse

How to optimize php code? The following article will introduce you to some methods of optimizing PHP code. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

How to optimize php code?

PHP code optimization

1. Try to be as static as possible

If a method can be static, declare it as static, and the speed can be increased by 1/4. Even when I tested, this increased by nearly three times.

Of course, this test method needs to be executed at level 100,000 or above for the effect to be obvious.

In fact, the main difference in efficiency between static methods and non-static methods is memory: static methods generate memory when the program starts, and instance methods (non-static methods) generate memory while the program is running, so static methods can be called directly. Instance methods must first create an instance and then call it. Static methods are very fast, but if they are used too much, they will take up memory.

Any language operates on memory and disk. As for whether it is object-oriented, it is just a question of the software layer. The bottom layer is the same, but the implementation method is different. Static memory is continuous because it is generated at the beginning of the program, while instance methods apply for discrete space, so of course it is not as fast as static methods.

Static methods always call the same memory. The disadvantage is that they cannot be automatically destroyed, but instantiation can be destroyed.

2. Echo is more efficient than print

Because echo has no return value and print returns an integer. Test:

echo
0.000929 - 0.001255 s (平均 0.001092 seconds)

print
0.000980 - 0.001396 seconds (平均 0.001188 seconds)

The difference is about 8%. Generally speaking, echo is faster.

Note: When echo outputs large strings, if there is no adjustment, performance will be seriously affected. Turning on Apache's mod_deflate for compression, or turning on ob_start to put the content into the buffer can improve performance issues.

3. Maximum number of loops

Set the maximum number of loops before the loop, not during the loop.

4. Destroy variables in time

Arrays and objects occupy special memory in PHP. This is caused by the underlying zend engine of PHP. Generally speaking, the memory utilization of PHP arrays is only 1/10. That is to say, an array with 100M of memory in C language requires 1G in PHP.

Especially in systems where PHP is used as a backend server, the problem of excessive memory consumption often occurs.

5. Avoid using magic methods like __get, __set, __autoload, etc.

(for reference only, subject to discussion)

For those starting with __ The functions are named magic functions, and these functions are triggered under specific conditions. In general, there are the following magic functions: __construct(), __destruct(), __get(), __set(), __unset(), __call(), __callStatic(), __sleep(), __wakeup(), __toString() , __set_state(), __clone(), __autoload().

In fact, 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 do a lot of Judging whether the file exists (you need to search in the path included in each include path), and judging whether the file exists requires disk I/O operations. As we all know, the efficiency of disk I/O operations is very low, so this is what makes The reason why the efficiency of the autoload mechanism is reduced.

Therefore, when we design the system, we need to define a clear mechanism for mapping class names to actual disk files. The simpler and clearer this rule is, the more efficient the autoload mechanism will be.

Conclusion: The autoload mechanism is not naturally inefficient. Only abuse of autoload and poorly designed autoload functions will lead to a reduction in efficiency.

So try to avoid using __autoload magic The method is open to question.

6. requirere_once() and include_once() are relatively resource intensive.

This is because requirere_once() and include_once() need to determine whether the file has been referenced, so Use it as much as possible. Commonly used require/include methods to avoid. Brother Niao has stated many times in his blog that try not to use require_once and include_once.

7. Use absolute paths in include and require

If a relative path is included, PHP will traverse the include_path to find the file.

Using absolute paths will avoid such problems, so it will take less time to resolve the operating system path.

8. Use $_SERVER['REQUSET_TIME']

If you need to get the script execution time, $_SERVER['REQUSET_TIME'] is better than time().

It is conceivable that one is ready to use directly, and the other requires the result obtained by the function.

9. Use built-in functions to replace regular expressions

If you can use PHP's internal string manipulation functions, try to use them instead of regular expressions, because Its efficiency is higher than regular.

It goes without saying that regular expressions consume the most performance.

Are there any useful functions that you missed? For example: strpbrk(), strncasecmp(), strpos(), strrpos(), stripos(), strripos().

strtr() function is used to convert specified characters. If all that need to be converted are single characters, use strings instead of arrays:

<?php
$addr = strtr($addr, "abcd", "efgh");       // good
$addr = strtr($addr, array(&#39;a&#39; => &#39;e&#39;, ));  // bad

Efficiency improvement: 10 times.

10、用strtr作字符替换

str_replace字符替换比正则替换preg_replace快,但strtr比str_replace又快1/4。

另外,不要做无谓的替换,即使没有替换,str_replace也会为其参数分配内存。很慢!

解决办法:用 strpos 先查找(非常快),看是否需要替换,如果需要,再替换。

效率:如果需要替换,效率几乎相等,差别在 0.1% 左右。如果不需要替换:用 strpos 快 200%。

11、用字符串而不是数组作为参数

如果一个函数既能接受数组,又能接受简单字符做为参数,那么尽量用字符作为参数。例如字符替换函数,参数列表并不是太长,就可以考虑额外写一段替换代码,使得每次传递参数都是一个字符,而不是接受数组做为查找和替换参数。大事化小,1+1>2。

12、最好不用@

用@掩盖错误会降低脚本运行速度,并且在后台有很多额外操作。用@比起不用,效率差距 3 倍。特别不要在循环中使用@,在 5 次循环的测试中,即使是先用error_reporting(0)关掉错误,在循环完成后再打开,都比用@快。

13、数组元素加引号

$row['id']$row[id]速度快7倍,建议养成数组键名加引号的习惯。

14、别在循环里用函数

例如:

for($x=0; $x < count($array); $x++) {
}

这种写法在每次循环的时候都会调用 count() 函数,效率大大降低,建议这样:

$len = count($array);
for($x=0; $x < $len; $x++) {
}

让函数在循环外面一次获得循环次数。

16、方法里建立局部变量

在类的方法里建立局部变量速度最快,几乎和在方法里调用局部变量一样快。

17、局部变量比全局变量快2倍

由于局部变量是存在栈中的,当一个函数占用的栈空间不是很大的时候,这部分内存很有可能全部命中cache,这时候CPU访问的效率是很高的。

相反,如果一个函数里既使用了全局变量又使用了局部变量,那么当这两段地址相差较大时,cpu cache需要来回切换,那么效率会下降。

18、局部变量而不是对象属性

建立一个对象属性(类里面的变量,例如:$this->prop++)比局部变量要慢3倍。

19、提前声明局部变量

建立一个未声明的局部变量要比一个已经定义过的局部变量慢9-10倍。

20、谨慎声明全局变量

声明一个未被任何一个函数使用过的全局变量也会使性能降低(和声明相同数量的局部变量一样)。PHP可能去检查这个全局变量是否存在。

21、类的性能和其方法数量没有关系

新添加10个或多个方法到测试的类后,性能没什么差异。

22、在子类里方法的性能优于在基类中

23、函数快于类方法

调用只有一个参数、并且函数体为空的函数,花费的时间等于7-8次$localvar++运算,而同一功能的类方法大约为15次$localvar++运算。

24、用单引号代替双引号会快一些

因为PHP会在双引号包围的字符串中搜寻变量,单引号则不会。

PHP 引擎允许使用单引号和双引号来封装字符串变量,但是它们的速度是有很大的差别的!使用双引号的字符串会告诉 PHP 引擎,首先去读取字符串内容,查找其中的变量,并改为变量对应的值。一般来说字符串是没有变量的,所以使用双引号会导致性能不佳。最好是使用字符串连接而不是双引号字符串。

$output = "This is a plain string";  // 不好的实践
$output = &#39;This is a plain string&#39;;  // 好的实践

$type = "mixed";                     // 不好的实践
$output = "This is a $type string";

$type = &#39;mixed&#39;;                     // 好的实践
$output = &#39;This is a &#39; . $type .&#39; string&#39;;

25、echo字符串用逗号代替点连接符更快些

echo可以把逗号隔开的多个字符串当作“函数”参数传入,所以速度会更快。(说明:echo是一种语言结构,不是真正的函数,故把函数加上了双引号)。例如:

echo $str1, $str2;       // 速度快
echo $str1 . $str2;      // 速度稍慢

26、尽量静态化

Apache/Nginx解析一个PHP脚本的时间,要比解析一个静态HTML页面慢2至10倍,所以尽量使页面静态化,或使用静态HTML页面。

27、使用缓存

Memchached或者Redis都可以。

高性能的分布式内存对象缓存系统,提高动态网络应用程序性能,减轻数据库的负担。

也对运算码 (OP code)的缓存很有用,使得脚本不必为每个请求做重新编译。

28、使用整型保存IP

使用ip2long()和long2ip()函数把IP地址转成整型后,再存放进数据库,而保存非字符型。

这几乎能降低1/4的存储空间。同时可以很容易对地址进行排序和快速查找;

29、检查email有效性

使用checkdnsrr()通过域名存在性来确认email地址的有效性,这个内置函数能保证每一个的域名对应一个IP地址。

30、使用MySQLi或PDO

mysql_*函数已经不被建议使用,建议使用增强型的mysqli_*系列函数或者直接使用PDO。

31、屏蔽敏感信息

使用error_reporting()函数来预防潜在的敏感信息显示给用户。

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

32、引用传递参数

通过参数地址引用使函数有多个返回值,在参数变量前加个“&”表示按地址传递,而非按值传递。

33、使用++$i递增

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

34、不要随便复制变量

有时候为了使 PHP 代码更加整洁,一些 PHP 新手(包括我)会把预定义好的变量复制到一个名字更简短的变量中,其实这样做的结果是增加了一倍的内存消耗,只会使程序更加慢。试想一下,在下面的例子中,如果用户恶意插入 512KB 字节的文字到文本输入框中,这样就会导致 1MB 的内存被消耗!

// 不好的实践
$description = $_POST[&#39;description&#39;];
echo $description;

// 好的实践
 echo $_POST[&#39;description&#39;];

35、使用选择分支语句

switch、case好于使用多个if、else if语句,并且代码更加容易阅读和维护。

36、用file_get_contents替代file、fopen、feof、fgets

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

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

38、优化Select SQL语句

在可能的情况下尽量少的进行insert、update操作(在update上,我被恶批过)。

39、尽可能的使用PHP内部函数

40、循环内部不要声明变量,尤其是大变量:对象

这好像不只是PHP里面要注意的问题吧?

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

42、循环用foreach效率更高

尽量用foreach代替while和for循环

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

44、mod_deflate压缩输出

打开apache的mod_deflate模块,可以提高网页的浏览速度。(提到过echo 大变量的问题)

45、数据库连接当使用完毕时应关掉,不要用长连接

46、split比exploade快

split()
0.001813 - 0.002271 seconds (avg 0.002042 seconds)

explode()
0.001678 - 0.003626 seconds (avg 0.002652 seconds)

The above is the detailed content of How to optimize php code?. For more information, please follow other related articles on the PHP Chinese website!

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