1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【PHP】array_searchとarray_keysの速度比較

Last updated at Posted at 2018-10-31

#array_searchとarray_keysの速度比較

  • 速度比較には https://paiza.io/ を使用
  • 繰り返し回数は1000回
  • for文は含まず、処理にかかる時間を計算

単純に比較

<?php
// 処理を繰り返すための関数
$repeatTestFunc = function ($func, $limit) {
    $time = 0;
    for ($i = 0; $i < $limit; $i++) {
        $start = microtime(true);
        $func();
        $time +=  (microtime(true) - $start);
    }
    return $time;
};

// 平均時間を取得するための関数
$averageTimeFunc = function ($processTime, $limit) {
    return ($processTime / $limit);
};


$array = ['red', 'blue', 'green', 'white', 'black'];

$func1 = function () use ($array) {
    $key = array_search('red', $array);
};

$func2 = function () use ($array) {
    $keyArr = array_keys($array, 'red');
};

$limit = 1000;

$t1 = $repeatTestFunc($func1, $limit);
$t2 = $repeatTestFunc($func2, $limit);

var_dump('array_search:' . $t1);
var_dump('array_keys:' . $t2);
?>

結果

string(32) "array_search:0.00043582916259766"
string(30) "array_keys:0.00046944618225098"

返り値を同じ条件にするため、array_keysの返り値の1つ目の要素を代入する想定で検証

<?php
// 処理を繰り返すための関数
$repeatTestFunc = function ($func, $limit) {
    $time = 0;
    for ($i = 0; $i < $limit; $i++) {
        $start = microtime(true);
        $func();
        $time +=  (microtime(true) - $start);
    }
    return $time;
};

// 平均時間を取得するための関数
$averageTimeFunc = function ($processTime, $limit) {
    return ($processTime / $limit);
};


$array = ['red', 'blue', 'green', 'white', 'black'];

$func1 = function () use ($array) {
    $key = array_search('red', $array);
};

$func2 = function () use ($array) {
    $keyArr = array_keys($array, 'red');
    $key = $keyArr[0];
};

$limit = 1000;

$t1 = $repeatTestFunc($func1, $limit);
$t2 = $repeatTestFunc($func2, $limit);

var_dump('array_search:' . $t1);
var_dump('array_keys:' . $t2);
?>

結果

string(32) "array_search:0.00042223930358887"
string(24) "array_keys:0.00048828125"
1
1
0

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?