同時優化在PHP函數,我改變爲什麼PHP中的投射和比較比is_ *更快?
if(is_array($obj)) foreach($obj as $key=>$value { [snip] }
else if(is_object($obj)) foreach($obj as $key=>$value { [snip] }
到
if($obj == (array) $obj) foreach($obj as $key=>$value { [snip] }
else if($obj == (obj) $obj) foreach($obj as $key=>$value { [snip] }
瞭解===
後,我改變了對
if($obj === (array) $obj) foreach($obj as $key=>$value { [snip] }
else if($obj === (obj) $obj) foreach($obj as $key=>$value { [snip] }
改變從芸,*鑄造每個測試導致重大加速(> 30%)。
據我所知,===
比==
快,因爲沒有強制要做,但爲什麼要比調用任何is _ * - 函數更快速地創建變量?
編輯: 既然大家問的正確性,我寫了這個小測試:
$foo=(object) array('bar'=>'foo');
$bar=array('bar'=>'foo');
if($foo===(array) $foo) echo '$foo is an array?';
if($bar===(object) $bar) echo '$bar is an object?';
它不打印任何錯誤,這兩個變量不得到改變,所以我覺得它的工作,但我已經準備好了,否則就說服了。
另一個編輯: Artefacto的節目給了我下面的數字:
PHP 5.3.2-1ubuntu4.2 (64bit) on a Core i5-750 with Xdebug Elapsed (1): 0.46174287796021/0.28902506828308 Elapsed (2): 0.52625703811646/0.3072669506073 Elapsed (3): 0.57169318199158/0.12708187103271 Elapsed (4): 0.51496887207031/0.30524897575378 Speculation: Casting and comparing can be about 1.7-4 times faster.
PHP 5.3.2-1ubuntu4.2 (64bit) on a Core i5-750 without Xdebug Elapsed (1): 0.15818405151367/0.214271068573 Elapsed (2): 0.1531388759613/0.25853085517883 Elapsed (3): 0.16164898872375/0.074632883071899 Elapsed (4): 0.14408397674561/0.25812387466431 Without Xdebug, the extra function call didn't matter anymore, so every test (except 3) ran faster.
PHP 5.3.2-1ubuntu4.2 on a Pentium M 1.6GHz Elapsed (1): 0.97393798828125/0.9062979221344 Elapsed (2): 0.39448714256287/0.86932587623596 Elapsed (3): 0.44513893127441/0.23662400245667 Elapsed (4): 0.38685202598572/0.82854390144348 Speculation: Casting an array is slower, casting an object can be faster, but might not be slower.
PHP 5.2.6-1+lenny8 on a Xeon 5110 Elapsed (1): 0.273758888245/0.530702114105 Elapsed (2): 0.276469945908/0.605964899063 Elapsed (3): 0.332523107529/0.137730836868 Elapsed (4): 0.267735004425/0.556323766708 Speculation: These results are similar to Artefacto's results, I think it's PHP 5.2.
解決辦法: 我使用的分析器(Xdebug的)由函數調用大約慢了3倍(即使不進行分析),但沒有影響鑄造和比較沒有所以鑄造和比較似乎更快,即使它不受調試器/分析器的影響。
如果我猜的話,它會是因爲避免函數調用的開銷。 – Amber 2010-06-05 20:36:42
您的替換不會導致相應的程序。例如,如果'$ obj'是一個對象,'is_array($ obj)'返回'false',但是可能'($ obj ==(array)$ obj)'計算爲'true'。 – Artefacto 2010-06-05 20:45:14
@Artefacto是的,這完全是真的。這也是我寫的,請看看我的回答,並給我一些反饋 – streetparade 2010-06-05 20:49:14