Marco Demaio Marco Demaio - 6 months ago 46
Javascript Question

Javascript fastest way to duplicate an Array - slice vs for loop

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 For loop:

for(var i = 0, len = original_array.length; i < len; ++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 therefore both arrays will have references to the same objects.
But this is not the point of this question.

I'm asking only about speed.

Dan Dan
Answer

There are at least 4 (!) principal ways to clone an array:

  • loop
  • constructor
  • slice / splice
  • concat

There are over 14 sub - ways. Browse the benchmark thread for them. Many holywars were fought to choose the best one among them... Benchmark is the only judge:

BENCHMARKS thread

Strange to see that Firefox 25, Safari 6, Safari for iOS 7 and IE 11 are still in the stone age and using a while loop is the fastest way for them. I suppose cloning in a single step using native methods is preferable because they are written in C / Assembler and open for internal optimizations (they should use direct memory block copying). This is already implemented in V8 and I predict that it should be implemented by others in future.

Quick answer is:

 var b = a.slice();

Using concat is correct as well.

This answer becomes outdated fast. Use benchmarks to check the actual situation

Comments