版权声明:本文为博主原创文章,如需转载请注明出处,谢谢。喜欢请关注哟~ https://blog.csdn.net/sjt223857130/article/details/80743412
通常,concat用于连接数组,但如果concat是将数组添加到数组的进程,则数组每次都会生成数组,并查看其他方法Array.prototype。 因为有一个叫做push.apply的东西。
测试代码1:
var a = [0, 1, 2, 3], b = [4, 5, 6, 7], i, count = 10000; console.time(); for (i = 0; i < count; i++) { a = a.concat(b); } console.timeEnd();
测试代码2:
var a = [0, 1, 2, 3], b = [4, 5, 6, 7], i, count = 10000; console.time(); for (i = 0; i < count; i++) { Array.prototype.push.apply(a, b); } console.timeEnd();
我们通过每次运行五次来测试上述文件。
结果
1次 | 2次 | 3次 | 4次 | 5次 | |
---|---|---|---|---|---|
concat | 200ms | 200ms | 201ms | 202ms | 201ms |
Array.prototype.push.apply | 3ms | 3ms | 2ms | 2ms | 3ms |
结论
我认为当需要大量连接序列时非常有用。
补充:如果数组只连接一次的情况下。
测试代码1:
var i, count = 100000; console.time(); for (i = 0; i < count; i++) { var a = [0, 1, 2, 3], b = [4, 5, 6, 7]; a = a.concat(b); } console.timeEnd();
测试代码2:
var i, count = 100000; console.time(); for (i = 0; i < count; i++) { var a = [0, 1, 2, 3], b = [4, 5, 6, 7]; Array.prototype.push.apply(a, b); } console.timeEnd();
结果
1次 | 2次 | 3次 | 4次 | 5次 | |
---|---|---|---|---|---|
concat | 10ms | 9ms | 10ms | 10ms | 9ms |
Array.prototype.push.apply | 15ms | 16ms | 15ms | 15ms | 15ms |