今天在找資料時看到這一篇,我心血來潮重做了一下這個實驗,結果發現差異沒有那麼明顯。
當然可能是因為我用的是PHP 5.2,或是機器是雙核心的關係,實際的最大差距也不過是2~3倍。

程式碼在下面:

<?php
//  呼叫測試
$測試 = array();
$陣列 = array();
$次數 = 100000;

function 函數(&$參數){
    return htmlentities($參數);
}

class 物件 {
    function __call($方法, $參數){
        return htmlentities(reset($參數));
    }
  function 函數(&$參數){
        return htmlentities($參數);
  }
  static function 靜態(&$參數){
        return htmlentities($參數);
  }
}

$函數 = '函數';
$物件 = &new 物件();
$參照 = array($物件, $函數);

for ($索引 = 0;$索引 < $次數;$索引++){
    $陣列[$索引] = &md5(uniqid(rand(), true));
}

//  測試開始
//  Native
$時間 = &microtime(true);
for ($索引 = 0;$索引 < $次數;$索引++){
    htmlentities($陣列[$索引]);
}
$測試['Native'] = microtime(true) - $時間;

//  函數
$時間 = &microtime(true);
for ($索引 = 0;$索引 < $次數;$索引++){
    函數($陣列[$索引]);
}
$測試['函數'] = microtime(true) - $時間;

//  $函數
$時間 = &microtime(true);
for ($索引 = 0;$索引 < $次數;$索引++){
    $函數($陣列[$索引]);
}
$測試['$函數'] = microtime(true) - $時間;

//  $物件->函數
$時間 = &microtime(true);
for ($索引 = 0;$索引 < $次數;$索引++){
    $物件->函數($陣列[$索引]);
}
$測試['$物件->函數'] = microtime(true) - $時間;

//  $物件->$函數
$時間 = &microtime(true);
for ($索引 = 0;$索引 < $次數;$索引++){
    $物件->$函數($陣列[$索引]);
}
$測試['$物件->$函數'] = microtime(true) - $時間;

//  物件::靜態
$時間 = &microtime(true);
for ($索引 = 0;$索引 < $次數;$索引++){
    物件::靜態($陣列[$索引]);
}
$測試['物件::靜態'] = microtime(true) - $時間;

//  物件->__call
$時間 = &microtime(true);
for ($索引 = 0;$索引 < $次數;$索引++){
    $物件->隨機($陣列[$索引]);
}
$測試['物件->__call'] = microtime(true) - $時間;

//  call_user_func_$函數
$時間 = &microtime(true);
for ($索引 = 0;$索引 < $次數;$索引++){
    call_user_func($函數, $陣列[$索引]);
}
$測試['call_user_func_$函數'] = microtime(true) - $時間;

//  call_user_func_$參照
$時間 = &microtime(true);
for ($索引 = 0;$索引 < $次數;$索引++){
    call_user_func($參照, $陣列[$索引]);
}
$測試['call_user_func_$參照'] = microtime(true) - $時間;

//  call_user_func_array_$函數
$時間 = &microtime(true);
for ($索引 = 0;$索引 < $次數;$索引++){
    call_user_func_array($函數, array($陣列[$索引]));
}
$測試['call_user_func_array_$函數'] = microtime(true) - $時間;

//  call_user_func_array_$參照
$時間 = &microtime(true);
for ($索引 = 0;$索引 < $次數;$索引++){
    call_user_func_array($參照, array($陣列[$索引]));
}
$測試['call_user_func_array_$參照'] = microtime(true) - $時間;

//  顯示結果
echo '<pre>';
print_r($測試);
echo '</pre>';
?>


PING:
TITLE: PHP5 的動態函數/行為調用效率測試
URL: http://blog.roodo.com/rocksaying/archives/2633503.html
IP: 0.0.0.0
BLOG NAME: 石頭閒語
DATE: 01/09/2007 10:25:06 AM
因為 HACGIS 沒測到 reflection 的部份,所以把我的效率測試碼也放上來供各位參考。
arrow
arrow
    全站熱搜

    HACGIS 發表在 痞客邦 留言(0) 人氣()