spread syntax vs slice method

喜欢而已 提交于 2019-12-03 05:26:43

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 sliceing and spreading 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)

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:

New versions of Chrome (72+) seem to have eliminated the performance gap. https://measurethat.net/Benchmarks/ListResults/2667

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 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().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!