【轉】JavaScript 高性能數組去重

原文地址:https://www.cnblogs.com/wisewrong/p/9642264.html

 

一、測試模版

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

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

複製代碼
// 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.... 惹不起惹不起...

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章