PHP echo performance

2019-07-16 11:45发布

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";

2条回答
smile是对你的礼貌
2楼-- · 2019-07-16 12:14

Oh no, this question again.

None of these perform the best.

They're all the same.

Moreover, none of these should be used ever.
It should be template, that outputs your data, and you have use it's features, not printing values from your business code directly.

And again, there is no speed difference.
No overloaded server will get no help from such "optimization". Not great one, nor even slightest. If you want to help an overloaded server, you have to profile its performance, not doing useless things.

查看更多
祖国的老花朵
3楼-- · 2019-07-16 12:18
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?';

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.

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.

For example this would work:

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';
查看更多
登录 后发表回答