关于javascript:javascript-合并数组的几种方式及性能差异

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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理