PHP回显性能 [英] PHP echo performance

查看:53
本文介绍了PHP回显性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些命令中哪个命令执行效果最好?最差?为什么?

Which of these commands will perform the best? Worst? And why?

echo 'A: '.$a.' B: '.$b.' C: '.$c;

echo 'A: ', $a, ' B: ', $b, ' C: ', $c;

echo "A: $a B: $b C: $c";


推荐答案

echo 'A: ', $a, ' B: ', $b, ' C: ', $c;

最快,因为这里字符串的所有部分都直接复制到输出流,而其他变体将涉及首先串联字符串部分。 连接表示必须为字符串的每个部分分配一个新的内存块,并将先前的字符串复制到其中。

will be fastest, because here all parts of a string are directly copied to the output stream, whereas the other variants would involve first concatenation the string parts. "Concatenation" means that for every part of the string a new chunk of memory must be allocated and the previous string copied into it.

我将通过以下示例进行说明。

I will illustrate it with the following example

echo 'Hallo', ' ', 'World', '!', "\n", 'How are you?';
// vs.
echo 'Hallo' . ' ' . 'World' . '!' . "\n" . 'How are you?';

第一个副本5个字节+ 1个字节+ 5个字节+ 1个字节+ 1个字节+ 12个字节到输出流,从而复制25个字节。
第二个创建一个具有5个字节的字符串,然后创建一个具有6个字节的字符串并将其复制5 + 1个字节,然后创建一个具有11个字节的字符串并将其复制6 + 5个字节,然后创建一个包含12个字节的字符串并将其复制11 + 1个字节,然后创建一个包含13个字节的字符串并将其复制12 + 1个字节,然后创建一个包含25个字节的字符串并将其复制13 + 12个字节,然后最终将这25个字节复制到输出缓冲区。那将是92个字节,并完成了更多的内存分配。

The first one copies 5 bytes + 1 byte + 5 bytes + 1 byte + 1 byte + 12 bytes to the output stream, thus copying 25 bytes. The second one creates a string with 5 bytes, then creates a string with 6 bytes and copies the 5 + 1 bytes into it, then creates a string with 11 bytes and copies the 6 + 5 bytes into it, then creates a string with 12 bytes and copies the 11 + 1 bytes into it, then creates a string with 13 bytes and copies the 12 + 1 bytes into it, then creates a string with 25 bytes and copies the 13 + 12 bytes into it and then eventually copies these 25 bytes to the output buffer. That would be 92 bytes copied and way more memory allocations done.

但是,实际上,您不必在意。我非常怀疑您的应用程序的瓶颈将是 echo 性能;)

But really, you shouldn't care about that. I very much doubt that the bottleneck of your application will be echo performance ;)

但是仍然是我在回声中使用逗号而不是串联运算符的原因:逗号在所有运算符优先级。这样,您就不必写括号。

But there still is a reason why I use echo with commas instead of concatenation operators: The comma has the lowest of all operator precedences. That way you never have to write parenthesis.

例如,这可以工作:

echo 'The script executed in ', microtime(true) - $startTime, ' seconds';

鉴于此无法按预期进行(我认为这是未定义的行为):

Whereas this would not work as expected (and is undefined behavior I think):

echo 'The script executed in ' . microtime(true) - $startTime . ' seconds';

这篇关于PHP回显性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆