Reputation: 25081
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?
Upvotes: 14
Views: 12097
Reputation: 890
In simple push append the array in the same reference, while concat doestn't effect the orignal array. Check out following snippet
let x = [1,2,3,4];
let y = x.concat(5);
// At this step y hold [1,2,3,4,5] and x remain unchanged to [1,2,3,4]
document.write('x=>'+x);
document.write('y=>'+y);
let z = x.push(5);
// At this step z hold 5 and x is now changed to [1,2,3,4,5]
document.write('x=>'+x);
document.write('z=>'+z);
Upvotes: 5
Reputation: 376
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.
The concat()
method returns a new array, with the values merged. This also avoids mutation side effects.
Upvotes: 12
Reputation: 887305
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)
Upvotes: 14