美文网首页
JavaScript之数组拼接的效率高低

JavaScript之数组拼接的效率高低

作者: 迦叶凡 | 来源:发表于2019-07-18 10:01 被阅读0次

    前言

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

    正文

    <script>
            // 测试数组拼接的效率问题
            let n = 500000
            function test1() {
                let test_s = +new Date()
                let arr = []
                for (let i = 0; i < n; i++) {
                    arr[i] = i
                }
                let test_e = +new Date()
                console.log('index:'+ (test_e - test_s) + 'ms       lenth:' + arr.length)
            }
            function test2() {
                let test_s = +new Date()
                let arr = []
                for (let i = 0; i < n; i++) {
                    arr.push(i)
                }
                let test_e = +new Date()
                console.log('push:'+ (test_e - test_s) + 'ms        lenth:' + arr.length)
            }
            let con_arr = []
            for (let i = 0; i < n; i++) {
                con_arr[i] = i
            }
            function test4() {
                let test_s = +new Date()
                let arr = []
                arr = arr.concat(con_arr)
                let test_e = +new Date()
                console.log('concat(arr):'+ (test_e - test_s) + 'ms     lenth:' + arr.length)
            }
            function test5() {
                let test_s = +new Date()
                let arr = []
                arr = [...arr, ...con_arr]
                let test_e = +new Date()
                console.log('es6...:'+ (test_e - test_s) + 'ms      lenth:' + arr.length)
            }
            test1()
            test2()
            test4()
            test5()
        </script>
    

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


    n=10000 n=100000 n=500000 n=1000000 n=5000000 n=10000000

    相关文章

      网友评论

          本文标题:JavaScript之数组拼接的效率高低

          本文链接:https://www.haomeiwen.com/subject/lxrklctx.html