DEV Community

Discussion on: Javascript Array.push is 945x faster than Array.concat 🤯🤔

Collapse
 
mykohsu profile image
mykohsu

There's a major problem that should be mentioned.

push(... arr)

Will stack overflow if your array is larger than the stack size.

Collapse
 
shiling profile image
Shi Ling

Wait... why? Stack as in execution stack or memory?

Collapse
 
johncip profile image
jmc

Execution stack. It's the same for apply:

> const a = [], b = new Array(10**6)
> Array.prototype.push.apply(a, b)
Thrown:
RangeError: Maximum call stack size exceeded

The problem is that function call arguments all need to go on the call stack, so that they can be bound to the called function's variables. Put another way, push.apply(a, [1,2,3]) --> a.push(1,2,3), where 1, 2, and 3 are assumed to fit in the call stack.

The max stack size is set by the OS & user, but generally small (a few hundred or thousand kb), since it's only meant to hold function call contexts.

So we can distinguish between cases where the array is actually a list of function arguments, or the push.apply usage, where the array is "just" data, and we're only able to use it with push because that function, for convenience, takes a variable number of arguments.

In order to use apply in the latter case, it's good to know up front that the array will be small.

Thread Thread
 
shiling profile image
Shi Ling

Oh I see!