Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop

后端 未结 22 1552
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 02:10

In order to duplicate an array in JavaScript: which of the following is faster to use?

###Slice method

var dup_array = original_array.slice();
<         


        
22条回答
  •  无人及你
    2020-11-22 02:47

    As @Dan said "This answer becomes outdated fast. Use benchmarks to check the actual situation", there is one specific answer from jsperf that has not had an answer for itself: while:

    var i = a.length;
    while(i--) { b[i] = a[i]; }
    

    had 960,589 ops/sec with the runnerup a.concat() at 578,129 ops/sec, which is 60%.

    This is the lastest Firefox (40) 64 bit.


    @aleclarson created a new, more reliable benchmark.

提交回复
热议问题