在php5中使用內(nèi)聯(lián)字符串與串聯(lián)的速度差異?(假設(shè)php5)考慮<?php
$foo = 'some words';
//case 1
print "these are $foo";
//case 2
print "these are {$foo}";
//case 3
print 'these are ' . $foo;?>1和2之間有很大差異嗎?如果沒有,那么在1/2和3之間呢?
3 回答

米脂
TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超3個(gè)贊
好吧,就像所有“現(xiàn)實(shí)生活中可能更快”的問題一樣,你無法擊敗現(xiàn)實(shí)生活中的考驗(yàn)。
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 = "these are " . $foo;}print timeFunc('Method1', 10) . "\n";print timeFunc('Method2', 10) . "\n";print timeFunc('Method3', 10) . "\n";
給它幾個(gè)運(yùn)行頁面,然后......
0.0035568
0.0035388
0.0025394
因此,正如預(yù)期的那樣,插值幾乎相同(噪聲水平差異,可能是由于插值引擎需要處理的額外字符)。直線連接約為速度的66%,這并不是很大的震撼。插值解析器將查找,無需執(zhí)行任何操作,然后使用簡單的內(nèi)部字符串concat完成。即使concat很昂貴,插值器仍然必須這樣做,在解析變量并修剪/復(fù)制原始字符串的所有工作之后。
Somnath的更新:
我將Method4()添加到上面的實(shí)時(shí)邏輯中。
function Method4() { $foo = 'some words'; for ($i = 0; $i < 10000; $i++) $t = 'these are ' . $foo;}print timeFunc('Method4', 10) . "\n";Results were:0.00147390.00155740.00119550.001169
當(dāng)你只是聲明一個(gè)字符串而不需要解析那個(gè)字符串時(shí),為什么要混淆PHP調(diào)試器來解析。我希望你明白我的觀點(diǎn)。
- 3 回答
- 0 關(guān)注
- 283 瀏覽
添加回答
舉報(bào)
0/150
提交
取消