概要
PHPでは,メソッドチェーンを使った処理のほうが遅くなると聞いたので,実際に処理時間を計測して比較してみました.
環境
- Macbook Pro (2018,i5,256GB)
- PHP 7.3.5 (Homebrew)
比較内容
次のパターンで計測しました.
- class内でメソッドチェーンを使用
- class内でメソッドチェーンを不使用
- インスタンスに対して,メソッドチェーンを使用
- インスタンスに対して,メソッドチェーンを不使用
- インスタンスに対して,メソッドチェーンが使えるが,あえて使わない
比較用コード
コード内の"..."では同様の処理を50000行実行しています.
class TestClass {
public $count;
public function __construct() {
$this->count = 0;
}
public function noReturnThis() {
$this->count += 1;
}
public function returnThis() {
$this->count += 1;
return $this;
}
public function callInClassChain() {
$this->returnThis()-> ... ->returnThis();
}
public function callInClassNoReturn() {
$this->noReturnThis();
...
$this->noReturnThis();
}
}
$test1 = new TestClass;
$test2 = new TestClass;
$test3 = new TestClass;
$test4 = new TestClass;
$test5 = new TestClass;
$time_start = microtime(true);
$test1->callInClassChain();
$time = microtime(true) - $time_start;
echo "クラス内チェーン:{$test1->count}:{$time}\n";
$time_start = microtime(true);
$test2->callInClassNoReturn();
$time = microtime(true) - $time_start;
echo "クラス内ノーチェーン:{$test2->count}:{$time}\n";
$time_start = microtime(true);
$test3->returnThis()-> ... ->returnThis();
$time = microtime(true) - $time_start;
echo "クラス外チェーン:{$test3->count}:{$time}\n";
$time_start = microtime(true);
$test4->noReturnThis();
...
$test4->noReturnThis();
$time = microtime(true) - $time_start;
echo "クラス外ノーチェーン:{$test4->count}:{$time}\n";
$time_start = microtime(true);
$test5->returnThis();
....
$test5->returnThis();
$time = microtime(true) - $time_start;
echo "クラス外ノーチェーン2:{$test5->count}:{$time}\n";
測定結果
数回計測を行い,中央値を取りました.
比は最も早かったクラス外ノーチェーンを基準にしたものです.
順位 | ケース | 処理時間(秒) | 比 |
---|---|---|---|
4 | クラス内チェーン | 0.0020990371704102 | 1.12 |
3 | クラス内ノーチェーン | 0.0020008087158203 | 1.07 |
5 | クラス外チェーン | 0.0024318695068359 | 1.30 |
1 | クラス外ノーチェーン | 0.0018730163574219 | 1 |
2 | クラス外ノーチェーン(returnあり) | 0.0019741058349609 | 1.05 |
まとめ
やはりメソッドチェーンを用いた処理は遅くなる傾向があるようです.しかしながら,クラス内でのチェーンはそこまで遅くならないようです.
また,遅くなると言っても5万回繰り返して数ミリ秒遅くなる程度なので,よほどのことがない限りは気にするる必要はないと思います.