spread syntax vs slice method
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 = { ...obj };
obj.foo === clone.foo // true
obj.baz === clone.baz // true
obj === clone // false (references are different)
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: