I was browsing the answers to this question: Can I dispatch an action in reducer? and in this answer, I see the following:
actionQueue = actionQueue.concat([asyncAction]);
which is essentially the same as:
actionQueue.push(asyncAction);
(ignoring that the concat
call is creating a new array and re-assigning it to actionQueue
, the result is the same -- an array with asyncAction
appended to it).
Initially, I thought that it (perhaps) performed better (somehow), and someone else was apparently wondering the same as they beat me to it in jsperf: Array .concat() vs. .push().
As the results of the jsperf testing show, the concat
method is significantly slower than push
(at least as far as Chrome is concerned).
Is there something I'm missing?
Is there a reason concat
would be preferred in this use case?
concat returns a new array while push returns the length of updated array. Because concat creates a new array to hold the result of merged arrays, it's slower than push . For small arrays, both methods do not produce a significant difference in term of performance.
The push() adds elements to the end of an array and returns the new length of the array. Thus your return here is invalid. The concat() method is used to merge arrays. Concat does not change the existing arrays, but instead returns a new array.
The push() method is generic. It only expects the this value to have a length property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.
It's a property from concat() that does the heavy lifting, “apply” just executes the method. So what you're saying is that the concat function on arrays (i.e. Array. protype. concat ([x]) will always reduce [x] by 1 array level i.e. if arr = [1,2] it will become 1,2 and if arr = [[1,2]] it will become [1,2]).
If some other code has a reference to the existing array in actionQueue
, using concat
will not affect that.
var a1 = [1];
var b1 = a1
a1 = a1.concat([2])
var a2 = [1];
var b2 = a2
a2.push(2)
console.log('b1', b1)
console.log('b2', b2)
The push()
method is a generic method similar to call()
or apply()
. It will mutate your array (or object), pushing a new value into it.
Push: MDN
The concat()
method returns a new array, with the values merged. This also avoids mutation side effects.
Concat: MDN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With