Is there any clean and efficient way to add the contents of one array directly to another array without making an intermediate/temporary copy of all the data?
For example, you can use .push()
to add the contents of one array directly onto another like this:
// imagine these are a both large arrays
let base = [1,2,3];
let data = [4,5,6]
base.push(...data);
But, that seemingly makes a copy of all the items in data
as it makes them arguments to .push()
. The same is true for .splice()
:
// imagine these are a both large arrays
let base = [1,2,3];
let data = [4,5,6]
base.splice(base.length, 0, ...data);
Both of these seem inefficient from a memory point of view (extra copy of all the data) and from an execution point of view (the data gets iterated twice).
Methods like .concat()
don't add the contents of one array to another, but rather make a new array with the combined contents (which copies the contents of both arrays).
I've got some big arrays with lots of manipulations and I'm trying to ease the burden on the CPU/garbage collector by avoiding unnecessary intermediate copies of things and I find it curious that I haven't found such a built-in operation. So far, my best option for avoiding unnecessary copies has been this:
// imagine these are a both large arrays
let base = [1,2,3];
let data = [4,5,6];
for (let item of data) {
base.push(item);
}
which seems like it's probably not as efficient in execution as it could be if it was one operation and obviously it's multiple lines of code when you'd like it to be one line.