I was trying to understand what is the difference between spread syntax vs slice method in the following approach.
suppose I want to make an actual copy of an array,
Those two methods aren’t actually equivalent though. Slice is a function on Array.prototype
and is aware of the array’s implementation. It will create a very efficient deep copy. More importantly though, .slice()
will preserve the sparseness information of your array.
In contrast, [...Array]
will simply create a new array from an iterable view of your existing array. Not necessarily as efficient.
Try this:
var a = [];
a.length = 3;
console.log("slice:", a.slice());
console.log("spread:", [...a]);
With Chrome Browser developer console, I get these results:
slice: (3) [empty × 3]
spread: (3) [undefined, undefined, undefined]
If your array is particularly huge+sparse, array.slice()
will be exceptionally fast. [...array]
will probably hang your browser.
Performance aside slice
is just a function on Array.prototype
so it will work only for arrays. Spread syntax on the other hand will work for any iterable (object which satisfy iterable protocol) so it will work out of the box on any String
, Array
, TypedArray
, Map
and Set
. You can also easily create custom iterables.
There is also a difference when it comes to slice
ing and spread
ing arrays with holes (sparse arrays). As you can see below, slice
will preserve sparseness while spread
will fill holes with undefined
.
Array(3) // produces sparse array: [empty × 3]
Array(3).slice() // produces [empty × 3]
[...Array(3)] // produces [undefined, undefined, undefined]
Spread syntax can also be used to make shallow clones of objects:
const obj = { foo: 'bar', baz: 42 };
const clone = { ...obj1 };
obj.foo === clone.foo // true
obj.baz === clone.baz // true
obj === clone // false (references are different)
New versions of Chrome (72+) seem to have eliminated the performance gap. https://measurethat.net/Benchmarks/ListResults/2667
Performance will depend on the engine where its' running. And as with most Javscript code, it will probably be running in various different engines. So, use whatever feels aesthetically better. For me that's spread.
...
is sheer beauty.
If you decide to go with slice, skip the 0, just say .slice()
.
Measuring in Chrome shows that slice is far more performant than the spread operator, with 67M operations per second against 4M operations per second. If you're building for Chrome or an Electron app (which uses Chromium) I'd go for slice, especially for big data and real time applications.
EDIT:
It seems like the Spread operator is now much faster, albeit still slower than Slice: