首頁  >  文章  >  後端開發  >  PHP array_search 和 in_array 函數效率問題

PHP array_search 和 in_array 函數效率問題

藏色散人
藏色散人轉載
2019-10-17 13:41:503535瀏覽

問題

在一個介面中,發現非常耗時,檢查原因發現 array_search 尋找陣列中的元素的 key 時,效率隨著陣列變大,耗時增加。特別是大數組時,非常耗時。在函數 in_array 也有這個問題。

解決方法

採用array_flip 翻轉後,用isset 取代in_array 函數,用$array[key] 取代array_search, 這樣能解決大數組超時耗時問題

以下是我從php 官網抄下來的筆記,可以觀察這兩個方法效率的差異

原始網址:https://www.php.net/manual/en/function. in-array.php

If you're working with very large 2 dimensional arrays (eg 20,000+ elements) it's much faster to do this...
$needle = 'test for this';
$flipped_haystack = array_flip($haystack);
if ( isset($flipped_haystack[$needle]) )
{
  print "Yes it's there!";
}
I had a script that went from 30+ seconds down to 2 seconds (when hunting through a 50,000 element array 50,000 times).
Remember to only flip it once at the beginning of your code though!

更正

有人提出意見說道,array_flip 效率比in_array 和array_search 高,做了一些實驗,確實如此。這一點是我原來沒有考慮到問題。這個解決辦法,適用於多次使用 in_array 和 array_search 函數,才有效。下面是自己做實驗的結果。感謝 @木偶指出的問題

結果:

原始方法:0.0010008811950684
新方法:0.0069980621337891

循環 5000 次

$array = array();
for ($i=0; $i<200000; $i++){
    ##随机字符串
    $array[$i] = get_rand().$i;
}
$str = $array[199999];
$time1 = microtime(true);
for ($i=0; $i<5000; $i++){
    array_search($str, $array);
}
$time2 = microtime(true);
echo '原始方法:'.($time2-$time1)."\n";
$time3 =  microtime(true);
$new_array = array_flip($array);
for ($i=0; $i<5000; $i++){
    isset($new_array[$str]);
}
$time4 = microtime(true);
echo '新方法:'.($time4-$time3);

結果:##

原始方法:2.9000020027161
新方法:0.008030891418457

以上是PHP array_search 和 in_array 函數效率問題的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:learnku.com。如有侵權,請聯絡admin@php.cn刪除