JS合并数组的方式有很多种,在这里介绍几种常用的方法,以及他们的性能差异
- 网上有很多人说Array.prototype.push.apply方式是最好的,但是亲测之后发现这种方式在数据量少的时候也不是最快的,数据量大的时候还会报错。
- 另外也有很多人说forEach方法是最快的,因为它没有创建新数组,亲测后也不是最快的。
- 很多人认为concat这种方式是最差的,但经过测试发现是最快的。
- 扩展运算符写法相对简洁但是性能最差。
这里使用的数据示例如下:
let arr1 = [], arr2 = [], arr3 = [], arr4 = [], arr5 = [];
for (let index = 0; index < 10000000; index++) {
arr1.push(index);
}
for (let index = 10000000; index < 20000000; index++) {
arr2.push(index);
}
arr3 = [...arr1];
arr4 = [...arr1];
arr5 = [...arr1];
方法一:
使用concat方式
function _concat(){
let start = (new Date()).getTime();
arr1 = arr1.concat(arr2);
let end = (new Date()).getTime();
console.log('_concat', end - start);
}
_concat();
// 最终耗时80ms
方式二:
使用扩展运算符
function _test(){
let start = (new Date()).getTime();
arr3 = [...arr3, ...arr2];
let end = (new Date()).getTime();
console.log('_test', end - start);
}
_test()
// 耗时350ms
方式三:
使用forEach
function _forEach(){
let start1 = (new Date()).getTime();
arr2.forEach(function(v){ arr4.push(v) });
let end1 = (new Date()).getTime();
console.log('_forEach', end1 - start1);
}
_forEach();
// 耗时280ms
方式四:
使用Array.prototype.push.apply
function _push_apply(){
let start1 = (new Date()).getTime();
arr5.push.apply(arr5, arr2)
let end1 = (new Date()).getTime();
console.log('_push_apply', end1 - start1);
}
_push_apply();
// 时间不确定数据量大时会导致Maximum call stack size exceeded
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。