先貼代碼php
<?php include 'SortClass.php'; $i = 0; $reward = []; while($i < 100000){ $a = mt_rand(100,999); $reward[] = ['id'=>$a, 'num'=>$a]; $i++; } SortClass::consumeTime('啓動計數'); $items = []; foreach($reward as $v){ $items[$v['id']] = [$v['id'],$v['num']]; } SortClass::consumeTime('foreach'); $items = []; $items = array_map(function($v){ return [$v['id'] => [$v['id'],$v['num']]]; },$reward); SortClass::consumeTime('array_map'); $items = []; while($i < sizeof($reward)){ $items[$reward[$i]['id']] = [$reward[$i]['id'],$reward[$i]['num']]; $i++; } SortClass::consumeTime('while'); $items = []; for($i = 0; $i < sizeof($reward); $i++){ $items[$reward[$i]['id']] = [$reward[$i]['id'],$reward[$i]['num']]; } SortClass::consumeTime('for'); $items = []; $items = array_column($reward, null, 'id'); SortClass::consumeTime('array_column'); ------------------- //打印時間方法 public static function consumeTime($remark = ''){ static $start , $end , $num = null; $num++; if(!$start){ $start = microtime(true); return true; } $end = microtime(true); var_dump("第 {$num} 次:- {$remark} - :" . bcsub($end,$start,4)); $start = microtime(true); }
再貼結果 遍歷1000個元素時nginx
10000個php7
10萬個測試
測試環境 php7.2.5 nginx win10code
能夠看出array_column效率最快,while次之,再而後foreach array_map最差。blog
可是可能常規遍歷基本不會超過幾千次,幾萬或更大的話其實也不太適合php來執行。因此便利性來講我的以爲仍是foreach比較方便,array_map的話非業務邏輯必要仍是少用比較好。rem
em.... 另外,單位是秒it