应该注意的是,当使用亚当·赖特的3个变量的例子的修改版本时,结果是相反的,前两个函数实际上更快,一致。这是在CLI上使用PHP 7.1:
function timeFunc($function, $runs)
{
$times = array();
for ($i = 0; $i < $runs; $i++)
{
$time = microtime();
call_user_func($function);
@$times[$i] = microtime() - $time;
}
return array_sum($times) / $runs;
}
function Method1()
{
$foo = 'some words';
$bar = 'other words';
$bas = 3;
for ($i = 0; $i < 10000; $i++)
$t = "these are $foo, $bar and $bas";
}
function Method2()
{
$foo = 'some words';
$bar = 'other words';
$bas = 3;
for ($i = 0; $i < 10000; $i++)
$t = "these are {$foo}, {$bar} and {$bas}";
}
function Method3()
{
$foo = 'some words';
$bar = 'other words';
$bas = 3;
for ($i = 0; $i < 10000; $i++)
$t = "these are " . $foo . ", " . $bar . " and " .$bas;
}
print timeFunc('Method1', 10) . "\n";
print timeFunc('Method2', 10) . "\n";
print timeFunc('Method3', 10) . "\n";
我也试过用'3'代替整数3,但是我得到了同样的结果。
$bas=3时:
0.0016254
0.0015719
0.0019806
0.0016495
0.0015608
0.0022755
值得注意的是,这些结果变化很大(我得到大约300%的变化),但平均值似乎相对稳定,几乎(10个案例中有9个)总是显示第一个2个方法的执行速度更快,方法2总是比方法1稍快。
总之:对于一个单独的操作(无论是插值还是级联)来说,对于组合操作来说并不总是正确的。