PHP中的字符串串联(其中有一个变量),哪一个性能更好


String concatenation in PHP (with a variable inside of it) , which one has a better performance?

我在PHP中有这两个代码:

$msgs = 5;
//These two types of string concatenation
echo 'You got ' . $msgs . ' messages';
echo "You got $msgs messages";

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

实例

测试

<?
$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!

真实情况

差异是小到有意义,我个人喜欢插值,读起来优雅快捷,由你决定!)