JavaScript之数组循环的效率高低

2019-07-18  本文已影响0人  迦叶凡

前言

简单证明下不同数组拼接的效率问题,下面上结果(注意:我只在谷歌浏览器上进行了测试)
先说结论:arr.concat(array) > arr.push > arr[i] > [...arr] > arr.concat(i)

正文

<script>
    // 测试数组循环效率
    // 先准备一个数组
    let n = 20000000
    let arr = []
    for (let i = 0; i < n; i++) {
      arr.push(i)
    }

    function test1() {
      let test_s = +new Date()
      let sum = 0
      for (let i = 0; i < arr.length; i++) {
        sum += arr[i]
      }
      let test_e = +new Date()
      console.log('普通for循环:' + (test_e - test_s) + 'ms      lenth:' + arr.length + '      sum=' + sum)
    }

    function test3() {
      let test_s = +new Date()
      let sum = 0
      arr.forEach(function (e) {
        sum += e
      })
      let test_e = +new Date()
      console.log('foreach循环:' + (test_e - test_s) + 'ms      lenth:' + arr.length + '      sum=' + sum)
    }

    function test4() {
      let test_s = +new Date()
      let sum = 0
      for (let i in arr) {
        sum += arr[i]
      }
      let test_e = +new Date()
      console.log('for-in:' + (test_e - test_s) + 'ms      lenth:' + arr.length + '      sum=' + sum)
    }

    function test5() {
      let test_s = +new Date()
      let sum = 0
      for (let e of arr) {
        sum += e
      }
      let test_e = +new Date()
      console.log('for-of循环:' + (test_e - test_s) + 'ms      lenth:' + arr.length + '      sum=' + sum)
    }

    function test6() {
      let test_s = +new Date()
      let sum = 0
      let i = -1
      let len = arr.length
      while (++i < len) {
        sum += arr[i]
      }
      let test_e = +new Date()
      console.log('while(源码常见版)循环:' + (test_e - test_s) + 'ms      lenth:' + arr.length + '      sum=' + sum)
    }
    test1()
    test3()
    test4()
    test5()
    test6()
  </script>

下面是几组数据的测试结果


10000 100000 500000 1000000 5000000 10000000 20000000
上一篇下一篇

猜你喜欢

热点阅读