<?php
class test {
public static function a() {}
public function b() {}
}
$obj = new test;
?>
test::a() - 類名直接呼叫靜態方法$obj->a() - 實例呼叫靜態方法$obj->b() - 實例呼叫實例方法<?php
$obj = new test;
$test_times = 100;
$times = 10000;
$effi1 = array();
$effi2 = array();
while ($test_times-- > 0) {
$time1 = microtime(true);
for ($i = 0; $i < $times; $i++) test::a();
$time2 = microtime(true);
for ($i = 0; $i < $times; $i++) $obj->a();
$time3 = microtime(true);
for ($i = 0; $i < $times; $i++) $obj->b();
$time4 = microtime(true);
$effi1[] = ($time3 - $time2) / ($time2 - $time1); // 實例靜態 / 類名靜態
$effi2[] = ($time4 - $time3) / ($time3 - $time2); // 實例方法 / 實例靜態
}
function avg($arr) {
return array_sum($arr) / count($arr);
}
echo avg($effi1) . "\n" . avg($effi2);
?>
| PHP 版本 | 類名靜態 / 實例靜態 | 實例靜態 / 實例方法 |
|---|---|---|
| 5.2.14 | 0.76 (類名快 24%) | 1.07 (實例方法慢 7%) |
| 5.3.x | 0.57 (類名快 43%) | 1.10 (實例方法慢 10%) |
$this 綁定、屬性訪問權限檢查等ClassName::method() 呼叫$obj->staticMethod()),語義不清且效能較差測試環境說明:基於 Windows 7 + php.exe,Apache 2.2 模組模式結果一致。核心執行引擎相同,Web 模式僅增加 SAPI 開銷,相對比例不變。