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

后端 未结 22 1503
佛祖请我去吃肉
佛祖请我去吃肉 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:35

    It depends on the length of the array. If the array length is <= 1,000,000, the slice and concat methods are taking approximately the same time. But when you give a wider range, the concat method wins.

    For example, try this code:

    var original_array = [];
    for(var i = 0; i < 10000000; i ++) {
        original_array.push( Math.floor(Math.random() * 1000000 + 1));
    }
    
    function a1() {
        var dup = [];
        var start = Date.now();
        dup = original_array.slice();
        var end = Date.now();
        console.log('slice method takes ' + (end - start) + ' ms');
    }
    
    function a2() {
        var dup = [];
        var start = Date.now();
        dup = original_array.concat([]);
        var end = Date.now();
        console.log('concat method takes ' + (end - start) + ' ms');
    }
    
    function a3() {
        var dup = [];
        var start = Date.now();
        for(var i = 0; i < original_array.length; i ++) {
            dup.push(original_array[i]);
        }
        var end = Date.now();
        console.log('for loop with push method takes ' + (end - start) + ' ms');
    }
    
    function a4() {
        var dup = [];
        var start = Date.now();
        for(var i = 0; i < original_array.length; i ++) {
            dup[i] = original_array[i];
        }
        var end = Date.now();
        console.log('for loop with = method takes ' + (end - start) + ' ms');
    }
    
    function a5() {
        var dup = new Array(original_array.length)
        var start = Date.now();
        for(var i = 0; i < original_array.length; i ++) {
            dup.push(original_array[i]);
        }
        var end = Date.now();
        console.log('for loop with = method and array constructor takes ' + (end - start) + ' ms');
    }
    
    a1();
    a2();
    a3();
    a4();
    a5();
    

    If you set the length of original_array to 1,000,000, the slice method and concat method are taking approximately the same time (3-4 ms, depending on the random numbers).

    If you set the length of original_array to 10,000,000, then the slice method takes over 60 ms and the concat method takes over 20 ms.

提交回复
热议问题