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';
for ($i = 0; $i < 10000; $i++)
$t = "these are $foo";
}
function Method2() {
$foo = 'some words';
for ($i = 0; $i < 10000; $i++)
$t = "these are {$foo}";
}
function Method3() {
$foo = 'some words';
for ($i = 0; $i < 10000; $i++)
$t = sprintf("these are %s", $foo);
}
function Method4() {
$foo = 'some words';
for ($i = 0; $i < 10000; $i++)
$t = "these are " . $foo;
}
function Method5() {
$foo = 'some words';
for ($i = 0; $i < 10000; $i++)
$t = 'these are ' . $foo;
}
print timeFunc('Method1', 10) . "\n";
print timeFunc('Method2', 10) . "\n";
print timeFunc('Method3', 10) . "\n";
print timeFunc('Method4', 10) . "\n";
print timeFunc('Method5', 10) . "\n";
RESULT:
0.0023114
0.002422
0.0072015
0.001946
0.0017625
但是這是 loop 10萬次才有一點點的差距.
結論是 method5(單 quote + concate string) 速度較佳! method3 (sprintf) 最慘!
inline 寫法有兩種, 這兩種都差不多, 所以就 codeing 時的手順上, 以 $foo 這種是比較好寫這也是多數人的寫法 , {$foo} 這種比較好閱讀.
若是在需求上需要加上換行的話, 在一個 strings 中用 inline 寫法把 \n 放在 quote 中, 這種速度卻又比 concate string 寫法來得快.
ps: 速度比較這種題目很多人都會陷入某種迷失, 每個人的環境/需求都不盡相同, 並不是最快的就是適合自己的.