PHP performance optimization example sharing

小云云
Release: 2023-03-21 14:02:01
Original
1556 people have browsed it

This article mainly shares with you PHP performance optimization examples. This article lists many points, hoping to help everyone.

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 1/4. 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 generate memory while the program is running, so static methods can be called directly, and instance methods must first generate instances. Calling methods through instances is very fast statically, but will take up more memory.
Any language operates on memory and disk. As for whether it is object-oriented, it is just a matter 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 the instance applies for discrete space, so of course it is not as fast as the static method.
Static methods always call the same piece of memory. The disadvantage is that it cannot be automatically destroyed, but can be destroyed by instantiation.

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 (average 0.001092 seconds )
Print
0.000980 - 0.001396 seconds (average 0.001188 seconds)
The difference is about 8%. Generally speaking, echo is faster.
Note that when echoing large strings, performance will be seriously affected if no adjustments are made. Use mod_deflate to open apached for compression or open ob_start to put the content into the buffer first.

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

All fools understand this.

4. Destroy variables to release memory, especially large arrays;

Arrays and objects occupy a lot of 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. In other words, 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 such as __get, __set, __autoload (for reference only, subject to discussion);

For functions starting with __, name them Magic functions, such functions are first accessed 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 compare the class name with the actual disk file (note, this refers to the actual disk file, not just file name), the system will have to make a large number of judgments about whether files exist (which need to be searched in the paths included in each include path), and judging whether files exist requires disk I/O operations. As we all know, disk I/O operations The efficiency of /O operations is very low, so this is the reason why the autoload mechanism is less efficient.

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 its efficiency.

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

6.requiere_once() consumes more resources;

This is because requirere_once needs to determine whether the file has been referenced), so it should be used as little as possible. Commonly used require/include methods to avoid.

7. Use absolute paths in includes and requires.

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. If you need to get the time when the script is executed, $_SERVER['REQUSET_TIME'] is better than time();

As you can imagine. One is ready-made and can be used directly, and the other requires the result obtained by the function.

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

Needless to say, regular expressions consume the most performance.
Are there any useful functions that you missed? For example: strpbrk()strncasecmp()strpos()/strrpos()/stripos()/strripos() speeds up strtr. If all that needs to be converted is a single character,
use a string instead of an array to do strtr:

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

Efficiency improvement: 10 times.

10.str_replace character replacement is faster than regular replacement preg_replace, but strtr is 1/4 faster than str_replace;

In addition, do not make unnecessary replacements. Even if there is no replacement, str_replace will be Its parameters allocate memory. very slow! Solution:
Use strpos to search first (very fast) to see if replacement is needed. If necessary, replace again. Efficiency: - If replacement is needed: The efficiency is almost equal, and the difference is about 0.1%.
If no replacement is required: using strpos is 200% faster.

11. The parameter is a string

If a function can accept both arrays and simple characters as parameters, such as a character replacement function, and the parameter list is not too long, you can consider writing additional A piece of replacement code so that each parameter passed is a character, instead of accepting arrays as search and replace parameters. Make big things small, 1+1>2;

12. It is best not to use @, using @ to cover up errors will reduce the running speed of the script;

Using @ actually involves a lot of operations in the background. The efficiency difference between using @ and not using @ is: 3 times. Especially do not use @ in a loop. In the test of 5 loops, even if you use error_reporting(0) to turn off the error first and then turn it on after the loop is completed, it is faster than using @.

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

It is recommended to develop the habit of adding quotes to array keys;

14. Don’t use functions in loops

For example, For($x=0; $x < count($array); $x), the count() function calculates outside first; you know the reason.

16. Creating local variables in class methods is the fastest, almost as fast as calling local variables in methods;

17. Creating a global variable is 2 slower than local variables times;

Since local variables are stored in the stack, when the stack space occupied by a function is not very large, it is very likely that this part of memory will all hit the cache. At this time, the efficiency of CPU access is very high. .
On the contrary, if both global variables and local variables are used in a function, then when the two addresses are very different, the CPU cache needs to switch back and forth, and the efficiency will decrease.
(I understand)

18. Creating an object property (a variable in a class) such as ($this->prop++) is 3 times slower than a local variable;

19 .Creating an undeclared local variable is 9-10 times slower than a defined local variable

20.Declaring a global variable that has not been used by any function will also reduce performance (and declare same number of local variables).

PHP may check whether this global variable exists;

21. The performance of the method has nothing to do with the number of methods defined in a class

Because I added 10 There is no difference in performance after adding multiple methods or methods to the tested class (these methods are before and after the test method);

22. The performance of the method in the subclass is better than that in the base class;

23. The time it takes to run a function that calls only one parameter and has an empty function body is equal to 7-8 $localvar++ operations, while a similar method (function in a class) runs equal to about 15 $localvar++ operations;

24 Use single quotes instead of double quotes to enclose strings, which is faster.

Because PHP will search for variables in the string surrounded by double quotes, single quotes will not.

The PHP engine allows the use of single quotes and double quotes to encapsulate string variables, but there is a big difference! Using double-quoted strings tells the PHP engine to first read the contents of the string, find the variables in it, and change them to the values ​​corresponding to the variables. Generally speaking, strings have no variables, so using double quotes will lead to poor performance. It is better to use string concatenation instead of double quoted strings.

BAD:
$output = "This is a plain string";
GOOD:
$output = &#39;This is a plain string&#39;;
BAD: 
$type = "mixed";
$output = "This is a $type string";
GOOD:
$type = &#39;mixed&#39;;
$output = &#39;This is a &#39; . $type .&#39; string&#39;;
Copy after login

25. It is faster to use commas instead of dot connectors when echoing strings.

echo 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).

例如echo $str1,$str2。

26.Apache解析一个PHP脚本的时间要比解析一个静态HTML页面慢2至10倍。

尽量多用静态HTML页面,少用脚本。

28.尽量使用缓存,建议用memcached。

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

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

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

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

30.使用checkdnsrr()通过域名存在性来确认部分email地址的有效性

这个内置函数能保证每一个的域名对应一个IP地址;

31.使用mysql_*的改良函数mysqli_*;

32.试着喜欢使用三元运算符(?:);

33.是否需要PEAR

在你想在彻底重做你的项目前,看看PEAR有没有你需要的。PEAR是个巨大的资源库,很多php开发者都知道;

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

理想的错误报告应该被完全禁用在php.ini文件里。可是如果你在用一个共享的虚拟主机,php.ini你不能修改,那么你最好添加error_reporting(0)函数,放在每个脚本文件的第一行(或用

require_once()来加载)这能有效的保护敏感的SQL查询和路径在出错时不被显示;

36.使用 gzcompress() 和gzuncompress()对容量大的字符串进行压缩(解压)在存进(取出)数据库时。

这种内置的函数使用gzip算法能压缩到90%;

37.通过参数变量地址得引用来使一个函数有多个返回值。

你可以在变量前加个“&”来表示按地址传递而非按值传递;

38. 完全理解魔术引用和SQL注入的危险。

Fully understand “magic quotes” and the dangers of SQL injection. I’m hoping that most developers reading this are already familiar with SQL injection. However, I list it here because it’s absolutely critical to understand. If you’ve never heard the term before, spend the entire rest of the day googling and reading.

39.某些地方使用isset代替strlen

当操作字符串并需要检验其长度是否满足某种要求时,你想当然地会使用strlen()函数。此函数执行起来相当快,因为它不做任何计算,只返回在zval 结构(C的内置数据结构,用于存储PHP变量)中存储的已知字符串长度。但是,由于strlen()是函数,多多少少会有些慢,因为函数调用会经过诸多步骤,如字母小写化(译注:指函数名小写化,PHP不区分函数名大小写)、哈希查找,会跟随被调用的函数一起执行。在某些情况下,你可以使用isset() 技巧加速执行你的代码。

(举例如下)if (strlen($foo) < 5) { echo “Foo is too short”
} (与下面的技巧做比较) if (!isset($foo{5})) { echo “Foo is too short”
}
Copy after login

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

40.使用++$i递增

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 preincrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend’s PHP optimizer. It is a 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.

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

40. 不要随便就复制变量

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

BAD:
$description = $_POST[&#39;description&#39;];
echo $description;
GOOD:
echo $_POST[&#39;description&#39;];
Copy after login

41 使用选择分支语句

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

42.在可以用file_get_contents替代file、fopen、feof、fgets

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

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

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

45.尽可能的使用PHP内部函数

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

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

47.多维数组尽量不要循环嵌套赋值;

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

50.对global变量,应该用完就unset()掉;

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

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

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

54、压缩输出:打开apache的mod_deflate模块,可以提高网页的浏览速度。

(提到过echo 大变量的问题)

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

56、split比exploade快

split()
0.001813 - 0.002271 seconds (avg 0.002042 seconds)
explode()
0.001678 - 0.003626 seconds (avg 0.002652 seconds)
Split can take regular expressions as delimiters, and runs faster too. ~23% on average.
Copy after login

以上都是关于php代码的优化,下面是从整体结构方面优化PHP性能:

整体结构方面优化PHP性能

1.将PHP升级到最新版

  提高性能的最简单的方式是不断升级、更新PHP版本。

2.使用分析器

  网站运行缓慢的原因颇多,Web应用程序极其复杂,让人扑朔迷离。而一种可能性在于PHP代码本身。这个分析器可以帮助你快速找出造成瓶颈的代码,提高网站运行的总体性能。

  Xdebug PHP extension提供了强大的功能,可以用来调试,也可以用来分析代码。方便开发人员直接跟踪脚本的执行,实时查看综合数据。还可以将这个数据导入到可视化的工具 KCachegrind中。

3.检错报告

  PHP支持强大的检错功能,方便你实时检查错误,从比较重要的错误到相对小的运行提示。总共支持13种独立的报告级别,你可以根据这些级别灵活匹配,生成用户自定义的检测报告。

4.利用PHP的扩展

Everyone has always complained that PHP content is too complex. In recent years, developers have made corresponding efforts to remove some redundant features in the project. Even so, the number of libraries and other extensions available is impressive. Some developers are even starting to consider implementing their own extensions.

5.PHP cache, use PHP accelerator: APC

Under normal circumstances, PHP scripts are compiled and executed by the PHP engine and will be converted into machine language, also known as is the operation code. If a PHP script gets the same result after compiling it over and over again, why not skip the compilation process completely?

You can achieve this through the PHP accelerator, which caches the machine code of the compiled PHP script. Allows code to be executed immediately upon request without going through a tedious compilation process.

For PHP developers, there are currently two available caching solutions. One is APC (Alternative PHP Cache, optional PHP cache), which is an open source accelerator that can be installed through PEAR. Another popular solution is Zend Server, which not only provides opcode caching technology, but also provides caching tools for corresponding pages.

6. Memory Cache

PHP usually plays an important role in retrieval and data analysis, and these operations may cause performance degradation. In fact, some operations are completely unnecessary, especially repeatedly retrieving some commonly used static data from the database. You may wish to consider using the Memcached extension to cache data in the short term. Memcached's extended cache works with the libMemcached library to cache data in RAM and also allows users to define the cache period, helping to ensure real-time updates of user information.

7.Content Compression

Almost all browsers support Gzip compression method. Gzip can reduce the output by 80%. The cost is about a 10% increase in CPU calculations. But what you gain is that not only the bandwidth occupied is reduced, but your page loading will become faster, optimizing the performance of your PHP site.
You can turn it on in PHP.ini
zlib.output_compression = On
zlib.output_compression_level = (level) (level may be a number between 1-9, you can set different numbers to make it Suitable for your site. )
If you use apache, you can also activate the mod_gzip module, which is highly customizable.

8. Server cache:

Mainly based on the static servers nginx and squid based on web reverse proxy, as well as the mod_proxy and mod_cache modules of apache2

9. Database optimization: database cache, etc.

By configuring the database cache, such as turning on QueryCache cache, when the query receives a query that is the same as before, the server will retrieve it from the query cache. Results, instead of re-analyzing and executing the last query
and data storage procedures, connection pool technology, etc.

Related recommendations:

Sharing of PHP performance optimization tips

Detailed examples of PHP performance optimization

Five PHP performance optimization tips

The above is the detailed content of PHP performance optimization example sharing. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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