PHP8.1の新機能First-class Callable Syntaxを試す

そんなに使わないかもですが、地味にありがたい。

<?php

class FirstClassExample{
    public function prn(){
        echo __CLASS__.' at '.microtime(true).PHP_EOL;
    }
}

$fc = new FirstClassExample();
$f = $fc->prn(...);
$f2 = [$fc, 'prn'];// 従来のCallableの作り方

$f();// FirstClassExample at 1638319564.9256
usleep(1000); // wait 1ms
$f2();// FirstClassExample at 1638319564.9275

上記を少々改造して従来の方法と直接呼出しとでパフォーマンス比較してみる

<?php

class FirstClassExample{
    public function prn(){
        return __CLASS__.' at '.microtime(true).PHP_EOL;
    }
}

function bench(Callable $cb, $loops):string{
    $start = microtime(true);
    for($i=0;$i<$loops;++$i){
        $cb();
    }
    $elapsed = microtime(true) - $start;
    return $elapsed;
}

$fc = new FirstClassExample();
$f1 = $fc->prn(...);
$f2 = [$fc, 'prn'];// 従来のCallableの作り方

echo $f1();// FirstClassExample at 1638319564.9256
usleep(1000); // wait 1ms
echo $f2();// FirstClassExample at 1638319564.9275

$loops = 100000000;

$elapsed_f1 = bench($f1, $loops);
echo '$f1(): '.$elapsed_f1.PHP_EOL;

$elapsed_f2 = bench($f2, $loops);
echo '$f2(): '.$elapsed_f2.PHP_EOL;

結果は下記のようになり$f1()のFirst-class Callable Syntaxのほうが若干速い模様。
ただし1億回実行して2秒の違いなので1回あたり0.02msの違い。
とはいえ読みやすく気持ちやや速いなら使う機会ありそう。

f1(): 40.633121013641
f2(): 42.691957950592

カテゴリー: php

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です