0
當比較運算的性能,這是我會怎麼做typicaly測試:更好的方式做簡單的性能測試
<?php
$w = 'world';
$start1 = microtime(true);
for($i=0;$i<10000;$i++)
echo 'Hello ' . $w . '!';
$end1 = microtime(true);
$start2 = microtime(true);
for($i=0;$i<10000;$i++)
echo "Hello $w!";
$end2 = microtime(true);
$start3 = microtime(true);
for($i=0;$i<10000;$i++)
echo 'Hello ' + $w + '!';
$end3 = microtime(true);
echo "\n\n\n";
echo 'Concatination: ' . ($end1 - $start1) . "\nInline Var: " . ($end2 - $start2) . "\nAddition Operator: " . ($end3 - $start3);
有沒有更好的方式做這些測試時,可能是一個更可靠的方法?看起來,如果我多次運行相同的測試,我可以得到完全不同的結果,例如我跑了上述幾次,這就是我得到的。
Concatination: 0.057300090789795
Inline Var: 0.092978954315186
Addition Operator: 0.090532064437866
Concatination: 0.10458517074585
Inline Var: 0.075299978256226
Addition Operator: 0.039528131484985
Concatination: 0.063031911849976
Inline Var: 0.07781195640564
Addition Operator: 0.022316932678223
Concatination: 0.079019069671631
Inline Var: 0.030484914779663
Addition Operator: 0.096056938171387
Concatination: 0.077842950820923
Inline Var: 0.052779912948608
Addition Operator: 0.037421941757202
Concatination: 0.084203004837036
Inline Var: 0.013757944107056
Addition Operator: 0.074331045150757
Concatination: 0.027930021286011
Inline Var: 0.05648398399353
Addition Operator: 0.049610137939453
Concatination: 0.041821956634521
Inline Var: 0.047034978866577
Addition Operator: 0.062538862228394
Concatination: 0.0071420669555664
Inline Var: 0.066315889358521
Addition Operator: 0.004756927490234
Concatination: 0.088988065719604
Inline Var: 0.022722959518433
Addition Operator: 0.06276798248291
正如您在每次運行時可能會看到的結果大不相同。
您選擇的字符串連接方法幾乎與您的應用程序的性能無關。當你試圖從字符串連接中擠出幾納秒的執行時間時,你可能會得到一個O(n^3)嵌套循環,或者在沒有索引的查詢中運行8秒。此外,你忘了第四種形式:echo'Hello',$ w,'!'; – 2009-07-14 02:14:43