JavaScript 高性能數組去重


中午和同事吃飯,席間討論到數組去重這一問題

我立刻就分享了我常用的一個去重方法,隨即被老大指出這個方法效率不高

回家后我自己測試了一下,發現那個方法確實很慢

於是就有了這一次的高性能數組去重研究

 

一、測試模版

數組去重是一個老生常談的問題,網上流傳着有各種各樣的解法

為了測試這些解法的性能,我寫了一個測試模版,用來計算數組去重的耗時

// distinct.js
 let arr1 = Array.from(new Array(100000), (x, index)=>{ return index }) let arr2 = Array.from(new Array(50000), (x, index)=>{ return index+index }) let start = new Date().getTime() console.log('開始數組去重') function distinct(a, b) { // 數組去重
} console.log('去重后的長度', distinct(arr1, arr2).length) let end = new Date().getTime() console.log('耗時', end - start)

這里分別創建了兩個長度為 10W 和 5W 的數組

然后通過 distinct() 方法合並兩個數組,並去掉其中的重復項

數據量不大也不小,但已經能說明一些問題了

 

二、Array.filter() + indexOf

這個方法的思路是,將兩個數組拼接為一個數組,然后使用 ES6 中的 Array.filter() 遍歷數組,並結合 indexOf 來排除重復項

function distinct(a, b) { let arr = a.concat(b); return arr.filter((item, index)=> { return arr.indexOf(item) === index }) }

這就是我被吐槽的那個數組去重方法,看起來非常簡潔,但實際性能。。。

是的,現實就是這么殘酷,處理一個長度為 15W 的數組都需要 8427ms

 

三、雙重 for 循環

最容易理解的方法,外層循環遍歷元素,內層循環檢查是否重復

當有重復值的時候,可以使用 push(),也可以使用 splice()

function distinct(a, b) { let arr = a.concat(b); for (let i=0, len=arr.length; i<len; i++) { for (let j=i+1; j<len; j++) { if (arr[i] == arr[j]) { arr.splice(j, 1); // splice 會改變數組長度,所以要將數組長度 len 和下標 j 減一
                len--; j--; } } } return arr }

但這種方法占用的內存較高,效率也是最低的

 

 

四、for...of + includes()

雙重for循環的升級版,外層用 for...of 語句替換 for 循環,把內層循環改為 includes()

先創建一個空數組,當 includes() 返回 false 的時候,就將該元素 push 到空數組中 

類似的,還可以用 indexOf() 來替代 includes()

function distinct(a, b) { let arr = a.concat(b) let result = [] for (let i of arr) { !result.includes(i) && result.push(i) } return result }

這種方法和 filter + indexOf 挺類似

只是把 filter() 的內部邏輯用 for 循環實現出來,再把 indexOf 換為 includes

所以時長上也比較接近

 

  

五、Array.sort()

首先使用 sort() 將數組進行排序

然后比較相鄰元素是否相等,從而排除重復項

function distinct(a, b) { let arr = a.concat(b) arr = arr.sort() let result = [arr[0]] for (let i=1, len=arr.length; i<len; i++) { arr[i] !== arr[i-1] && result.push(arr[i]) } return result }

這種方法只做了一次排序和一次循環,所以效率會比上面的方法都要高

 

  

六、new Set()

ES6 新增了 Set 這一數據結構,類似於數組,但 Set 的成員具有唯一性

基於這一特性,就非常適合用來做數組去重了

function distinct(a, b) { return Array.from(new Set([...a, ...b])) }

那使用 Set 又需要多久時間來處理 15W 的數據呢?

喵喵喵??? 57ms ??我沒眼花吧??

然后我在兩個數組長度后面分別加了一個0,在 150W 的數據量之下...

居然有如此高性能且簡潔的數組去重辦法?!

 

七、for...of + Object

這個方法我只在一些文章里見過,實際工作中倒沒怎么用

首先創建一個空對象,然后用 for 循環遍歷

利用對象的屬性不會重復這一特性,校驗數組元素是否重復

function distinct(a, b) { let arr = a.concat(b) let result = [] let obj = {} for (let i of arr) { if (!obj[i]) { result.push(i) obj[i] = 1 } } return result }

當我看到這個方法的處理時長,我又傻眼了

15W 的數據居然只要 16ms ??? 比 Set() 還快???

然后我又試了試 150W 的數據量...

emmmmmmm.... 惹不起惹不起...


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM