Javascript fastest way to duplicate an Array

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.


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

  • loop
  • slice
  • Array.from()
  • concat
  • spread operator, etc. (so slow, forget it for now)
  • There has been a huuuge BENCHMARKS thread, providing following information:

  • for blink browsers slice() is the fastest method, concat() is a bit slower, and while loop is 2.4x slower.

  • for other browsers while loop is the fastest method, since those browsers don't have internal optimizations for slice and concat .

  • This remains true in Jul 2016.

    Below are simple scripts that you can copy-paste into your browser's console and run several times to see the picture. They output milliseconds, lower is better.

    while loop

    n = 1000*1000;
    start = + new Date();
    a = Array(n); 
    b = Array(n); 
    i = a.length;
    while(i--) b[i] = a[i];
    console.log(new Date() - start);
    

    slice

    n = 1000*1000;
    start = + new Date();
    a = Array(n); 
    b = a.slice();
    console.log(new Date() - start);
    

    Please note that these methods will clone the Array object itself, array contents however are copied by reference and are not deep cloned.

    origAr == clonedArr //returns false
    origAr[0] == clonedArr[0] //returns true
    

    Technically slice IS the fastest way, HOWEVER it is even faster if you add the 0 begin index.

    myArray.slice(0);
    

    is faster than,

    myArray.slice();
    

    http://jsperf.com/cloning-arrays/3


    那么es6的方式呢?

    arr2 = [...arr1];
    
    链接地址: http://www.djcxy.com/p/48364.html

    上一篇: 将NumPy数组转储到csv文件中

    下一篇: JavaScript最快的方式来复制一个数组