• 微信公众号：美女很有趣。 工作之余，放松一下，关注即送10G+美女照片！

# 数组性能问题分析总结

3小时前 2次浏览

### 数组的操作避免出现O(n^2)的复杂度

``````
Array.prototype.every()

Array.prototype.find()

Array.prototype.findIndex()

Array.prototype.forEach()

Array.prototype.map()

Array.prototype.reduce()

Array.prototype.some()

``````

#### Case 1 嵌套数组搜索操作

``````

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));

``````

``````
// 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));

``````

#### Case 2 concat的性能问题

``````
const arrayA = Array.from({ length: 10000 }, (v, i) => i);

const result = {};

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];

}

});

``````