Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript array copying, concat vs slice, which one is better? [closed]

Tags:

javascript

there are two different ways to copy a array, using Array.concat or Array.slice,

for example:

var a = [1, 2, 3],

    c1 = [].concat(a),

    c2 = a.slice(0);

which way is better?

like image 950
caiwf Avatar asked Jul 23 '13 07:07

caiwf


2 Answers

For clarity, you should use the method that is the documented method of taking a copy of an array (or portion thereof):

var c2 = a.slice(0);

On any decent browser the performance difference will be negligible, so clarity should be the deciding factor.

like image 156
Alnitak Avatar answered Nov 18 '22 21:11

Alnitak


In terms of performance, the difference between the two options are minimal, according to a jsperf.com test.

like image 40
David Pärsson Avatar answered Nov 18 '22 22:11

David Pärsson