spread syntax vs slice method

2019-04-21 07:33发布

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, I can probably easily do it using spread syntax

var fruits = ["Banana", "Chips" , "Orange", "Lemon", "Apple", "Mango"]
var newCitrus = [...fruits]

If I console.log this

["Banana", "Chips", "Orange", "Lemon", "Apple", "Mango"] 

but I can also create a copy of an array using the slice method. Considering the same array above, if I do something like this...

var citrus = fruits.slice(0);

and then console log it, it will give me exactly the same array which I would've got through spread syntax

["Banana", "Chips", "Orange", "Lemon", "Apple", "Mango"] 

Since both of them takes about the same time to code/write, What is the difference here? which approach should I usually choose?

4条回答
淡お忘
2楼-- · 2019-04-21 07:41

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

查看更多
Rolldiameter
3楼-- · 2019-04-21 07:44

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.

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)
查看更多
倾城 Initia
4楼-- · 2019-04-21 07:48

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

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-04-21 07:49

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.

Measure results

查看更多
登录 后发表回答