cliのphpでメソッドの呼び出しにどのくらい時間がかかるのか計測してみた。
インスタンスメソッドは、クラスのインスタンスを生成しないと呼び出せないメソッド。
クラスメソッドはインスタンスを生成しなくても呼べるメソッド。
- 条件
1,000,000回メソッドを呼び出す。
100回計測してその平均を出力
- 結果
| test | process time[sec] |
|---|---|
| instance method | 0.18120812892914 |
| class method | 0.16903691053391 |
| class method(インスタンス参照) | 0.17322729587555 |
インスタンスメソッドの方が遅い。
クラスメソッドもインスタンス名で参照する方が遅い。
ちなみにインスタンスを生成するのにかかる時間はこの程度の小さいクラスだと計測できない。
今回は実験的に行ったので、局所的な結果。
本来であれば、システム全体でのパフォーマンスを調査すべきである。
環境によって違うこともあるかも。
test.php
<?php
// Testクラス
class Test{
// instance method
public function ins(){
;
}
// class method
static public function cls(){
;
}
}
// 試行回数
const CALL_MAX = 1000000;
const SUM_MAX = 100;
// instance method
$summary = array();
$test = new Test();
for ($j=0; $j<SUM_MAX; $j++){
$begin = microtime(true);
for ($i=0; $i<CALL_MAX; $i++){
$test->ins();
}
$finish = microtime(true);
echo $j.":".($finish - $begin)."[sec]\n";
$summary[] = ($finish - $begin);
}
echo "instance method ".(array_sum($summary)/SUM_MAX)."[sec]\n";
//class method
$summary = array();
for ($j=0; $j<SUM_MAX; $j++){
$begin = microtime(true);
for ($i=0; $i<CALL_MAX; $i++){
Test::cls();
}
$finish = microtime(true);
echo $j.":".($finish - $begin)."[sec]\n";
$summary[] = ($finish - $begin);
}
echo "class method ".(array_sum($summary)/SUM_MAX)."[sec]\n";
//class method
$summary = array();
$test = new Test();
for ($j=0; $j<SUM_MAX; $j++){
$begin = microtime(true);
for ($i=0; $i<CALL_MAX; $i++){
$test->cls();
}
$finish = microtime(true);
echo $j.":".($finish - $begin)."[sec]\n";
$summary[] = ($finish - $begin);
}
echo "class method ".(array_sum($summary)/SUM_MAX)."[sec]\n";
// instance
$begin = microtime(true);
$test = new Test();
$finish = microtime(true);
echo "instance new ".($begin - $begin)."[sec]\n";