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

3次阅读

共计 1186 个字符,预计需要花费 3 分钟才能阅读完成。

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
正文完
 0