re: Javascript Array.push is 945x faster than Array.concat 🤯🤔 VIEW POST


Just thought I'd put this out here as I didn't see any mention of it yet.

Mozilla's JavaScript Documentation Reference actually makes mention about adding elements to arrays.

Using apply to append an array to another

We can use push to append an element to an array. And, because push accepts a variable number of arguments, we can also push multiple elements at once.

But, if we pass an array to push, it will actually add that array as a single element, instead of adding the elements individually, so we end up with an array inside an array. What if that is not what we want? concat does have the behaviour we want in this case, but it does not actually append to the existing array but creates and returns a new array.

apply to the rescue!

(Source: developer.mozilla.org/en-US/docs/W...)

... and then they go on to say ...

Merging two arrays

"This example uses apply() to push all elements from a second array."

"Do not use this method if the second array (moreVegs in the example) is very large, because the maximum number of parameters that one function can take is limited in practice. See apply() for more details."

(source: developer.mozilla.org/en-US/docs/W...)

code of conduct - report abuse