I want to concatenate two arrays into one. I have found two functions can do the job; one is jQuery.merge() and the other one is the JavaScript built in function concat(). They seem to do the same thing, and I found this. It says: “Merge creates a smaller footprint because it loops through the original array and adds the new items. Concat is a built-in Javascript function and should be faster, but has a larger footprint.” I am not sure if this statement is true, and are there any other differences?
I want to concatenate two arrays into one. I have found two functions can
Share
That quote is right and the two functions do not actually do the same thing, one merges two arrays into the one (first param), and the second builds a new array from both.
The “footprint” that it is referring to, is the max amount of memory that will be in use at any time. Since merge, is only going to duplicate the second array, it should use less memory, since at any time, it will only need to have 2 arrays in memory.
The built in function will need to have 3 arrays, and the new array will have to be the size of both arrays that are being concatenated.
Assuming 1000 elements in array A and B, and the merged array as C:
Less memory could be faster if there was a lot of memory in use, less moves could also be faster.
Some tests I found