4 ms·
How about [...array1, ...array2] vs Array.concat. Or does 1 just use 2 under the hood?
by KitDuncan 7y ago
How about [...array1, ...array2] vs Array.concat. Or does 1 just use 2 under the hood?
- braythwayt 7y agoThe issue here is that the author wants to merge one array into another, so they wrote a = a.concat(b), but that is implemented as: temp = a.concat(b) a = temp In creating `temp`, JS copies all the elements of a and all the elements of b. Whereas, a.push(...b) Only copies all the elements of b. The code you propose copies all the elements of a and b, so it wouldn’t be faster.
- azhu 7y agoI 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.