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

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

    In ES6, you can simply utilize the Spread syntax.

    Example:

    let arr = ['a', 'b', 'c'];
    let arr2 = [...arr];
    

    Please note that the spread operator generates a completely new array, so modifying one won't affect the other.

    Example:

    arr2.push('d') // becomes ['a', 'b', 'c', 'd']
    console.log(arr) // while arr retains its values ['a', 'b', 'c']
    
    0 讨论(0)
  • 2020-11-22 02:53

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

    My results on Internet Explorer 8 are 156, 782, and 750, which would indicate slice is much faster in this case.

    0 讨论(0)
  • 2020-11-22 02:53

    Benchmark time!

    function log(data) {
      document.getElementById("log").textContent += data + "\n";
    }
    
    benchmark = (() => {
      time_function = function(ms, f, num) {
        var z = 0;
        var t = new Date().getTime();
        for (z = 0;
          ((new Date().getTime() - t) < ms); z++)
          f(num);
        return (z)
      }
    
      function clone1(arr) {
        return arr.slice(0);
      }
    
      function clone2(arr) {
        return [...arr]
      }
    
      function clone3(arr) {
        return [].concat(arr);
      }
    
      Array.prototype.clone = function() {
        return this.map(e => Array.isArray(e) ? e.clone() : e);
      };
    
      function clone4(arr) {
        return arr.clone();
      }
    
    
      function benchmark() {
        function compare(a, b) {
          if (a[1] > b[1]) {
            return -1;
          }
          if (a[1] < b[1]) {
            return 1;
          }
          return 0;
        }
    
        funcs = [clone1, clone2, clone3, clone4];
        results = [];
        funcs.forEach((ff) => {
          console.log("Benchmarking: " + ff.name);
          var s = time_function(2500, ff, Array(1024));
          results.push([ff, s]);
          console.log("Score: " + s);
    
        })
        return results.sort(compare);
      }
      return benchmark;
    })()
    log("Starting benchmark...\n");
    res = benchmark();
    
    console.log("Winner: " + res[0][0].name + " !!!");
    count = 1;
    res.forEach((r) => {
      log((count++) + ". " + r[0].name + " score: " + Math.floor(10000 * r[1] / res[0][1]) / 100 + ((count == 2) ? "% *winner*" : "% speed of winner.") + " (" + Math.round(r[1] * 100) / 100 + ")");
    });
    log("\nWinner code:\n");
    log(res[0][0].toString());
    <textarea rows="50" cols="80" style="font-size: 16; resize:none; border: none;" id="log"></textarea>

    The benchmark will run for 10s since you click the button.

    My results:

    Chrome (V8 engine):

    1. clone1 score: 100% *winner* (4110764)
    2. clone3 score: 74.32% speed of winner. (3055225)
    3. clone2 score: 30.75% speed of winner. (1264182)
    4. clone4 score: 21.96% speed of winner. (902929)
    

    Firefox (SpiderMonkey Engine):

    1. clone1 score: 100% *winner* (8448353)
    2. clone3 score: 16.44% speed of winner. (1389241)
    3. clone4 score: 5.69% speed of winner. (481162)
    4. clone2 score: 2.27% speed of winner. (192433)
    

    Winner code:

    function clone1(arr) {
        return arr.slice(0);
    }
    

    Winner engine:

    SpiderMonkey (Mozilla/Firefox)

    0 讨论(0)
  • 2020-11-22 02:56

    Remember .slice() won't work for two-dimensional arrays. You'll need a function like this:

    function copy(array) {
      return array.map(function(arr) {
        return arr.slice();
      });
    }
    
    0 讨论(0)
提交回复
热议问题