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?
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()
.Performance aside
slice
is just a function onArray.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 anyString
,Array
,TypedArray
,Map
andSet
. You can also easily create custom iterables.Spread syntax can also be used to make shallow clones of objects:
New versions of Chrome (72+) seem to have eliminated the performance gap. https://measurethat.net/Benchmarks/ListResults/2667
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.