上篇说了静态方法的使用,在PHP中使用可以使用::调用静态方法和public的非静态函数,其效率不容小觑:
下面是使用pear::benchmark包测试代码:
<?php
set_time_limit(0);
require_once "Benchmark/Timer.php";
class Test {
function nostat() {
return 99 * 99;
}
static function isstat() {
return 99 * 99;
}
static function stataa() {
return self::nostat();
}
static function statbb() {
return self::isstat();
}
}
$timer = new Benchmark_Timer(TRUE);
$timer->start();
$timer->setMarker('startNotStatic');
for ($i = 0; $i < 1000000; $i++) {
Test::nostat();
}
$timer->setMarker('endNotStatic');
$timer->setMarker('startIsStatic');
for ($i = 0; $i < 1000000; $i++) {
Test::isstat();
}
$timer->setMarker('endIsStatic');
$timer->setMarker('startstataa');
for ($i = 0; $i < 1000000; $i++) {
Test::isstat();
}
$timer->setMarker('endstataa');
$timer->setMarker('startstatbb');
for ($i = 0; $i < 1000000; $i++) {
Test::isstat();
}
$timer->setMarker('endstatbb');
$timer->stop();
$timer->display();
测试结果如下
| time index | ex time | % | |
| Start | 1294579240.91868900 | – | 0.00% |
| startNotStatic | 1294579240.91869600 | 0.000007 | 0.00% |
| endNotStatic | 1294579243.12920500 | 2.210509 | 49.12% |
| startIsStatic | 1294579243.12923000 | 0.000025 | 0.00% |
| endIsStatic | 1294579243.88850800 | 0.759278 | 16.87% |
| startstataa | 1294579243.88854200 | 0.000034 | 0.00% |
| endstataa | 1294579244.64993700 | 0.761395 | 16.92% |
| startstatbb | 1294579244.64996500 | 0.000028 | 0.00% |
| endstatbb | 1294579245.41862600 | 0.768661 | 17.08% |
| Stop | 1294579245.41865800 | 0.000032 | 0.00% |
| total | – | 4.499969 | 100.00% |
不使用static关键字比使用效率差3倍!