数组性能问题分析总结
文章转自豆皮范儿-数组性能问题分析总结
数组的操作避免出现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