Difference between using a spread syntax (…) and p

2020-02-24 12:49发布

问题:

I have two arrays,

const pets = ["dog", "cat", "hamster"]

const wishlist = ["bird", "snake"]

I want to append wishlist to pets, which can be done using two methods,

Method 1:

pets.push.apply(pets,wishlist)

Which results in: [ 'dog', 'cat', 'hamster', 'bird', 'snake' ]

Method 2:

pets.push(...wishlist)

Which also results in: [ 'dog', 'cat', 'hamster', 'bird', 'snake' ]

Is there is a difference between these two methods in terms of performance when I deal with larger data?

回答1:

Both Function.prototype.apply and the spread syntax may cause a stack overflow when applied to large arrays:

let xs = new Array(500000),
 ys = [], zs;

xs.fill("foo");

try {
  ys.push.apply(ys, xs);
} catch (e) {
  console.log("apply:", e.message)
}

try {
  ys.push(...xs);
} catch (e) {
  console.log("spread:", e.message)
}

zs = ys.concat(xs);
console.log("concat:", zs.length)

Use Array.prototype.concat instead. Besides avoiding stack overflows concat has the advantage that it also avoids mutations. Mutations are considered harmful, because they can lead to subtle side effects.

But that isn't a dogma. If you are wihtin a function scope and perform mutations to improve performance and relieve garbage collection you can perform mutations, as long as they aren't visible in the parent scope.



回答2:

Apart from what ftor pointed out, Array.prototype.concat is, on average, at least 1.4x faster than the array spread operator.

See results here: https://jsperf.com/es6-add-element-to-create-new-array-concat-vs-spread-op

You can run the test on your own browser and machine here: https://www.measurethat.net/Benchmarks/Show/579/1/arrayprototypeconcat-vs-spread-operator



回答3:

Interpreting the question as which is more performant in general, using .push() as an example it looks like apply is [only slightly] faster (except for MS Edge, see below).

Here's a performance test on just the overhead on calling a function dynamically for the two methods.

function test() { console.log(arguments[arguments.length - 1]); }
var using = (new Array(200)).fill(null).map((e, i) => (i));

test(...using);

test.apply(null, using)

I tested in Chrome 71.0.3578.80 (Official Build) (64-bit), FF 63.0.3 (64-bit), & Edge 42.17134.1.0, and these were my resulsts after running them a few times on their own The initial results were always skewed one way or the other

As you can see Edge seems to have a better implementation for apply than it does for ... (but don't try to compare the results across browsers, we cant tell whether Edge has a better apply than the others, a worse ..., or a bit of both from this data).
Given this, unless you're targeting Edge specifically, I'd say go with ... just as it reads cleaner, especially if you need to pass an object back in to apply for this.

It's possible that it's dependent on the size of the array, too, so like @Jaromanda X said, do your own testing and change 200 if you need to really make sure.


The other answers interpreted the question as which would be better for .push() specifically, and get caught up on the 'problem' being solved, simply recommending to just use .concat(), which is basically the standard why are you doing it that way? which can irk some people coming from google that aren't looking for solutions to do with .push() (say, Math.max, or your own custom function).



回答4:

For appending to a large array the spread operator is vastly faster. I don't know how @ftor / @Liau Jian Jie drew their conclusions, possibly bad tests.

Chrome 71.0.3578.80 (Official Build) (64-bit), FF 63.0.3 (64-bit), & Edge 42.17134.1.0

It makes sense since concat() makes a copy of the array and doesn't even attempt to use the same memory.

The thing about "mutations" doesn't seem to be based on anything; if you're overwriting your old array, concat() has no benefits.

The only reason to not use ... would be stack overflow, I agree with the other answers that you can't use ... or apply.
But even then just using a for {push()} is more or less twice as fast as concat() in all browsers and wont overflow.
There's no reason to use concat() unless you need to keep the old array.



回答5:

With push you are appending to the existing array, with spread operator you are creating a copy.

a=[1,2,3]
b=a
a=[...a, 4]
alert(b);

=> 1, 2, 3

 a=[1,2,3]
b=a
a.push(4)
alert(b);

=> 1, 2, 3, 4

push.apply as well:

a=[1,2,3]
c=[4]
b=a
Array.prototype.push.apply(a,c)
alert(b);

=> 1, 2, 3, 4

concat is a copy

a=[1,2,3]
c=[4]
b=a
a=a.concat(c)
alert(b);

=> 1, 2, 3

By reference is preferable, especially for larger arrays.

Spread operator is a fast way of doing a copy which traditionally would be done with something like:

a=[1,2,3]
b=[]
a.forEach(i=>b.push(i))
a.push(4)
alert(b);

=> 1, 2, 3

If you need a copy, use the spread operator, it's fast for this. Or use concat as pointed out by @ftor. If not, use push. Keep in mind, however, there are some contexts where you can't mutate. Additionally, with any of these functions you will get a shallow copy, not a deep copy. For deep copy you will need lodash. Read more here : https://slemgrim.com/mutate-or-not-to-mutate/



回答6:

if you are using ES2015 then the spread operator is the way to go. Using the spread operator your code looks less verbose and much cleaner compared to other approach. When it comes to speed, I believe there will be little to choose between both the approaches.