Fastest way to add multiple elements to an Array / Vector

In a simple situation, where you wish to add many elements to an Array or Vector, you might just do:

However, the sizes of both Arrays are manipulated for each loop, which will have an adverse impact on speed and memory usage. So, we could cache the length of the input Array and not manipulate it:

But we’re still growing the size of the output Array incrementally, which is very bad. Since we know input.length in advance, we could grow the output Array to its new size just once, before the loop:

This is OK, but still involves a loop. If only we could push multiple elements into the push method in one go. Well, we can – enter the apply method. Since Array.push accepts multiple arguments (something rarely used) and apply allows us to pass an Array of arguments to any Function, one line and we’re done:

This works out faster and more memory efficient than the other methods. It works nicely for Vectors, too. If anyone has a faster method of doing this, do let me know.

InterServer Web Hosting and VPS

Leave a Reply