Re: [請益] 多個array 排序很慢

看板PHP作者 (人都有秘密)時間10年前 (2015/09/02 13:02), 編輯推噓1(105)
留言6則, 2人參與, 最新討論串2/2 (看更多)
※ 引述《CuCuGi (咕咕雞)》之銘言: : 大家好 小弟最近碰到排序的問題 : 主要是用於 fb的讚數排列 : usort($postArray,'sortByLikeCount'); : function sortByLikeCount($a, $b) : { : return ($a["likeCount"] <= $b["likeCount"]) ? -1 : 1; : } : 發現如果array過於大量(八萬筆左右)會排很久... : (之前有參考github上python的寫法 : postArray.sort(key=lambda x: x["likeCount"], reverse=True) : 發現排列非常的快) : 不知道在php中要怎麼修改才能更快的完成排序呢?謝謝各位 試試以下 echo "initial: ". microtime() ."<br />" ; $postArray = array() ; for($i = 0 ; $i < 100000 ; $i++) { $postArray[$i]["id"] = $i+1 ; $postArray[$i]["likeCount"] = rand(1,1000) ; } echo "initial END: ".microtime() ."<br />" ; // 排序 1 echo "Sort 1 Start: ".microtime() ."<br />" ; $total = array() ; foreach ($postArray as $key => $row) { $total[$key] = $row['likeCount'] ; } array_multisort($total, SORT_DESC, $postArray) ; echo "Sort 1 END: ".microtime() ."<br />" ; // 排序 2: 你的方法 echo "Sort 2 Start:".microtime() ."<br />" ; usort($postArray,'sortByLikeCount'); function sortByLikeCount($a, $b) { return ($a["likeCount"] <= $b["likeCount"]) ? -1 : 1; } echo "Sort 2 END: ".microtime() ."<br />" ; echo "END" ; -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.35.82.87 ※ 文章網址: https://www.ptt.cc/bbs/PHP/M.1441170147.A.A69.html

09/03 15:28, , 1F
推實測,但兩個方法要分開測
09/03 15:28, 1F

09/03 15:29, , 2F
第一個已經排好第二個就省很多時間
09/03 15:29, 2F

09/03 18:00, , 3F
第一個是遞減排第二個是遞增排?
09/03 18:00, 3F

09/04 15:11, , 4F
我忘了改 Sort 1 的遞增、遞減。
09/04 15:11, 4F

09/04 15:13, , 5F
10萬筆測下來,Sort 1 就是比 Sort 2 快上 1 秒,
09/04 15:13, 5F

09/04 15:14, , 6F
原Po看到可以試試看 :)
09/04 15:14, 6F
文章代碼(AID): #1LveBZff (PHP)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
文章代碼(AID): #1LveBZff (PHP)