3 ms·
I believe you misunderstand. The question refers to whether or not using the spread syntax only would result in similar performance gains as seen when moving fr
by azhu 7y ago
I believe you misunderstand. The question refers to whether or not using the spread syntax only would result in similar performance gains as seen when moving from .concat to .push with the spread.
const arraysToMerge = [ arr1, arr2, arr3, ... arrN ];
const spreadMergeFn = (reduced, arr) => [ ...reduced, ...arr ];
const spreadPushMergeFn = (reduced, arr) => reduced.push(...arr);
const merged = arraysToMerge.reduce(________, []);
Pure spreading will be slower. Using push lets you skip that first spread of what you've accumulated so far in favor of mutating a reference. I suspect that the above code using push will not run correctly though. Would need to get under the hood of .reduce to see, but it should break.
My current personal opinion is to use flat() if possible.
// these produce identical data structures
[ arr1, arr2, arr3 ].flat()
[ ...arr1, ...arr2, ...arr3 ]
arr1.slice().push(...arr2.push(...arr3))
- braythwayt 7y agoIf you think a misunderstanding may be afoot, let me be as explicit as possible. I do not believe that moving from: a = a.concat(b) To: a = [...a, ...b] Would give the same performance gains as moving to: a.push(...b) Because [...a, ...b] creates a new array, and copies the elements of both a and b into it. Old-timers will say that we had this exact same conversation about Java and strings way back in the day. Using a StringBuffer was faster for this kind of thing up and until Java started detecting when your use of string catenation could be replaced by a StringBuffer.