[英]Advanced JavaScript Array Concatenation - Performance
I'm trying out two different ways of joining two arrays and using huge arrays to judge their performances but I'm getting an error on the second option and I don't understand why. 我正在尝试两种不同的方式来连接两个数组,并使用巨大的数组来判断它们的性能,但是第二个选项却出现了错误,我不明白为什么。
I first filled both with 10,000,000 elements with values equal to their index. 我首先用值等于其索引的10,000,000个元素填充了这两个元素。
var arr1 = [];
var arr2 = [];
for (var i = 0; i < 10000000; i++) {
arr1[i] = i;
}
for (var i = 0; i < 10000000; i++) {
arr2[i] = i;
}
Option 1 completes fine in ~520ms: 选项1可以在约520ms内完成:
var newArr = arr1.concat(arr2);
Option 2 though throws the following error: 选项2会引发以下错误:
Array.prototype.push.apply(arr1, arr2);
Error: 错误:
/private/var/folders/j6/3fs5_k3n17z_0j2xrwj6sphw0000gn/T/CodeRunner/Untitled 9.js:12
Array.prototype.push.apply(arr1, arr2);
^
RangeError: Maximum call stack size exceeded
at Object.<anonymous> (/private/var/folders/j6/3fs5_k3n17z_0j2xrwj6sphw0000gn/T/CodeRunner/Untitled 9.js:12:22)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Function.Module.runMain (module.js:467:10)
at startup (node.js:136:18)
at node.js:963:3
Edit 编辑
Per one of the comments, I changed Option 2 to: 根据评论之一,我将选项2更改为:
setTimeout(function () {
Array.prototype.push.apply(arr1, arr2);
}, 0);
And I'm still getting: 而且我仍然得到:
/private/var/folders/j6/3fs5_k3n17z_0j2xrwj6sphw0000gn/T/CodeRunner/Untitled 9.js:16
Array.prototype.push.apply(arr1, arr2);
^
RangeError: Maximum call stack size exceeded
at null._onTimeout (/private/var/folders/j6/3fs5_k3n17z_0j2xrwj6sphw0000gn/T/CodeRunner/Untitled 9.js:16:23)
at Timer.listOnTimeout (timers.js:92:15)
The apply()
method unrolls provided array to arguments list. apply()
方法将提供的数组展开到参数列表。 ECMAScript specification itself have no limits on amount of arguments for function, but most JS engines have implementation-specifc limits because they use fixed or limited size structure for each function call on their internal stack for performance purposes. ECMAScript规范本身对函数的参数数量没有限制,但是大多数JS引擎都有特定于实现的限制,因为出于性能目的,它们对内部堆栈上的每个函数调用使用固定或有限大小的结构。 Though this limit is generally pretty high, it is certainly well below 10000000 arguments and that's why you get error "Maximum call stack size exceeded".
尽管此限制通常很高,但肯定低于10000000个参数,这就是为什么会出现错误“超出最大调用堆栈大小”的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.