文章轉自豆皮范兒-數組性能問題分析總結
數組的操作避免出現O(n^2)的復雜度
數組用來搜索元素的方法時間復雜度為O(n)。運行時間的增長速度與數據大小的增長速度相同,常用的如下
Array.prototype.every()
Array.prototype.find()
Array.prototype.findIndex()
Array.prototype.forEach()
Array.prototype.map()
Array.prototype.reduce()
Array.prototype.some()
如果將這些方法用在for循環內,或者兩個方法嵌套使用,就會造成O(n^2)的復雜度,造成嚴重的性能問題。
Case 1 嵌套數組搜索操作
// bad case 嵌套了數組搜索操作
const arrayA = Array.from({length: 10000}, (v, i) => i);
const arrayB = Array.from({length: 10000}, (v, i) => i * 2);
const result = arrayA.filter((v) => arrayB.every((u) => u !== v));
優化方法:使用Set或者Map方法進行數組的搜索操作
// good case 使用Set.has方法,代替Array.prototype.every()
const arrayA = Array.from({length: 10000}, (v, i) => i);
const arrayB = Array.from({length: 10000}, (v, i) => i * 2);
const set = new Set(arrayB)
const result = arrayA.filter((v) => !set.has(v));
二者的性能比較:數組大小為10000的時候,二者的性能差距已經有800倍左右
Case 2 concat的性能問題
const arrayA = Array.from({ length: 10000 }, (v, i) => i);
const result = {};
// bad case 每次concat都會新生產一個數組,會有較大的性能消耗
arrayA.forEach((a) => {
result.children = (result.children || []).concat(a);
});
// good case 復用已有的數組
arrayA.forEach((a) => {
if (result.children) {
result.children.push(a);
} else {
result.children = [a];
}
});
二者的性能比較:數組大小為10000的時候,二者的性能差距已經有1600倍
Case 3 創建數組操作的性能比較
幾種創建10000個元素數組方法的速度比較
可以看到實際速度最快的還是for循環的方法,其它Array.from
、解構
等一行實現的方法,實際速度並不快
在線JS性能比較平台
在線比較兩段代碼的性能,以每秒執行次數(ops/s)為指標 https://jsbench.me
字節跳動數據平台前端團隊,在公司內負責大數據相關產品的研發。我們在前端技術上保持着非常強的熱情,除了數據產品相關的研發外,在數據可視化、海量數據處理優化、web excel、WebIDE、私有化部署、工程工具都方面都有很多的探索和積累,有興趣可以與我們聯系。