PHP中的字符串连接(内部有变量),哪一个具有更好的性能?

时间:2014-10-03 21:25:29

标签: php performance concatenation string-concatenation

我在PHP中有这两个代码:

$msgs = 5;
//These two types of string concatenation

echo 'You got ' . $msgs . ' messages';

echo "You got $msgs messages";

1 个答案:

答案 0 :(得分:0)

让我们做一些新的测试,真的很简单

Live example

测试

<?
$str1 = $str2 = "";

for ($i=0; $i < 10000; $i++) {
    $start = microtime(true);
    $str1 .= 'You got ' . $i . ' messages';
    $str1_test[] = microtime(true) - $start;
}

echo "Dotted: " . ($str1_result = array_sum($str1_test) / 10000);

echo PHP_EOL;

for ($i=0; $i < 10000; $i++) {
    $start = microtime(true);
    $str2 .= "You got {$i} messages";
    $str2_test[] = microtime(true) - $start;
}

echo "Interpolated: " . ($str2_result = array_sum($str2_test) / 10000);
echo PHP_EOL . ($str2_result < $str1_result ? "Interpolation" : "Dot") . " is faster!";

结果

Dotted: 1.1234998703003E-6
Interpolated: 1.2600898742676E-6
Dot is faster!

真实事实

不同之处在于小有意义,我个人喜欢插值,优雅而且阅读速度更快,取决于你! ;)