views:

50

answers:

3

In order to duplicate an Array in Javascript,

does anyone know (and maybe tested) if it's faster to use slice method:

var dup_array = original_array.slice();

or doing a for loop:

for(var i = 0, l = original_array.lenght; i < l; ++i)
   dup_array[i] = original_array[i];

UPDATE: (just to clarify myself) I know both ways do only a shallow copy: if original_array contains references to objects, objects won't be cloned, but only the references will be copied therefor both arrays will have refrences to the same objects. But this is not the point of this question.

I'm asking only about speed.

+1  A: 

Take a look at: link. It's not about speed, but comfort. Besides as you can see you can only use slice(0) on primitive types.

To make an independent copy of an array rather than a copy of the refence to it, you can use the array slice method.

Example:

To make an independent copy of an array rather than a copy of the refence to it, you can use the array slice method.

var oldArray = ["mip", "map", "mop"];
var newArray = oldArray.slice();

To copy or clone an object :

function cloneObject(source) {
    for (i in source) {
        if (typeof source[i] == 'source') {
            this[i] = new cloneObject(source[i]);
        }
        else{
            this[i] = source[i];
  }
    }
}

var obj1= {bla:'blabla',foo:'foofoo',etc:'etc'};
var obj2= new cloneObject(obj1);

Source: link

Margus
The *primitive types* comment applies to the `for` loop in the question as well.
patrick dw
if I were copying an array of objects, I would expect the new array to reference the same objects rather than cloning the objects.
lincolnk
+1  A: 

It depends on broswer, if you look at the link below there is a rough guide to performance of each: http://weblogs.asp.net/alexeigorkov/archive/2008/02/18/array-prototype-slice-vs-manual-array-creation.aspx

kyndigs
`arguments` is not a proper array and he's using `call` to force `slice` to run on the collection. results may be misleading.
lincolnk
Moreover the link referes to quite old browsers. Anyway +1 thanks!
Marco Demajo
Yeh I meant to mention that in my post that these stats would probably change now with the broswers improving, but it gives a general idea.
kyndigs
+3  A: 

I put together a quick demo. http://jsbin.com/agugo3/edit

my results on IE8 are 156/782/750, which would indicate slice is much faster in this case.

lincolnk
Cool, easy to read test! Thanks +1
Marco Demajo
Yeap, I tested your code also on IE7, FF3.6 and Chrome5, slice looks 5xFASTER. On Safari4 is a bit slower slice.
Marco Demajo