問(wèn)題
在一個(gè)接口中,發(fā)現(xiàn)非常耗時(shí),排查原因發(fā)現(xiàn) array_search 查找數(shù)組中的元素的 key 時(shí),效率隨著數(shù)組變大,耗時(shí)增加。特別是大數(shù)組時(shí),非常耗時(shí)。在函數(shù) in_array 也有這個(gè)問(wèn)題。
解決辦法
采用 array_flip 翻轉(zhuǎn)后,用 isset 代替 in_array 函數(shù),用 $array[key] 替代 array_search, 這樣能解決大數(shù)組超時(shí)耗時(shí)問(wèn)題
下面是我從 php 官網(wǎng)抄下來(lái)的筆記,可以觀察這兩個(gè)方法效率的差異
原網(wǎng)址: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!
更正
有人提出意見(jiàn)說(shuō)道,array_flip 效率比 in_array 和 array_search 高,做了一些實(shí)驗(yàn),確實(shí)如此。這點(diǎn)是我原來(lái)沒(méi)有考慮到問(wèn)題。這個(gè)解決辦法,適用于多次使用 in_array 和 array_search 函數(shù),才有效。下面是自己做實(shí)驗(yàn)的結(jié)果。感謝 @木偶指出的問(wèn)題
<?php $array = array(); for ($i=0; $i<200000; $i++){ ##隨機(jī)字符串 $array[$i] = get_rand().$i; } $str = $array[150000]; $time1 = microtime(true); array_search($str, $array); $time2 = microtime(true); echo '原始方法:'.($time2-$time1)."n"; $time3 = microtime(true); $new_array = array_flip($array); isset($new_array[$str]); $time4 = microtime(true); echo '新方法:'.($time4-$time3);
結(jié)果:
原始方法:0.0010008811950684 新方法:0.0069980621337891
循環(huán) 5000 次
$array = array(); for ($i=0; $i<200000; $i++){ ##隨機(jī)字符串 $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);
結(jié)果:
原始方法:2.9000020027161 新方法:0.008030891418457