LoginSignup
2
0

More than 1 year has passed since last update.

【PHP】処理速度測定方法 ところでin_arrayってほんとに遅いの?

Last updated at Posted at 2022-11-14

in_arrayを使うなら、連想配列にしてでもissetを使った方が速いという記事を散見します
可読性のよいin_arrayをできれば使いたいので測定してみました

目次

処理速度の測り方
issetとin_array 検索に使うならどっちが速いのか?
issetの測定
in_arrayの測定
測定結果
結論

処理速度の測り方

とてもシンプル

// 実行環境 PHP v7.1.8

// 現在時刻をマイクロ秒まで取得
$start = microtime(true);

// --- ここに測定したい処理 ---

$end = microtime(true);

// 指数表記回避にsprintf()で桁数を6に指定
var_dump('XXXを検索 : ' . sprintf("%.6f",($end - $start)) . '秒' );

issetとin_array 検索に使うならどっちが速いのか?

検索用配列をつくる

$arr = [];
for( $i = 0; $i < 100; ++$i ){
  $arr[] = 'TEST' . (string)$i;
}

issetの測定

// issetで'TEST99'を検索
$search = false;
$start = microtime(true);

// issetで検索する場合は連想配列にする必要がある
// キーと値を反転させる
$tmpArr = array_flip($arr);

if(isset($tmpArr['TEST99'])) {
 $search = true;    
}

$end = microtime(true);

in_arrayの測定

// in_arrayで'TEST99'を検索
$search = false;
$start = microtime(true);

if(in_array('TEST99' ,$arr)) {
    $search = true;
};

$end = microtime(true);

測定結果

in_arrayは遅いのでissetを使った方がいい とよく耳にするが、

連想配列に直す必要がある場合はin_arrayの方が速かった

// 配列の要素数が100

// array_flipで連想配列に
string(37) "issetでTEST99を検索 : 0.000006秒"

string(40) "in_arrayでTEST99を検索 : 0.000002秒"

foreachで連想配列に直した場合は、更に遅くなる

// 配列の要素数が100

// foreachで連想配列に
string(37) "issetでTEST99を検索 : 0.000011秒"

string(40) "in_arrayでTEST99を検索 : 0.000002秒"

ちなみに、配列の要素が多いほど配列生成のコストが大きくなりin_arrayと差がひらく

// 配列の要素数が10000

// array_flipで連想配列に
string(39) "issetでTEST9999を検索 : 0.000296秒"

string(42) "in_arrayでTEST9999を検索 : 0.000051秒"

結論

検索は、連想配列に直してissetするならin_arrayの方が速い

2
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0