js中性能更好的在數組頭部插入大量數據

今天閒着無聊測試了一下js數組splice方法的性能發現:當數組的長度大於100000的時候整個頁面會出於比較長的卡死狀態,故試着寫了個性能更好的方法來實現批量在數組頭部插入數據:css

let splice = function (arr) {
    let cache = arr || []
    return {
        add: function (value) {
            cache.push(value)
        },
        get: function () {
            return cache.reverse()
        }
    }
}

和ramda、原生splice的性能比較:數組

clipboard.png

測試代碼以下:性能

<script src="https://cdn.bootcss.com/ramda/0.25.0/ramda.min.js"></script>
<script>
let splice = function (arr) {
    let cache = arr || []
    return {
        add: function (value) {
            cache.push(value)
        },
        get: function () {
            return cache.reverse()
        }
    }
}
    
let startTime = null;
let useTime = null;
var arr = [];
var len = 100000;
let arrT = splice(arr)
startTime = performance.now()
for(let i = 0; i < len; i++) {
    arrT.add(i)
}
arr = arrT.get()
useTime = performance.now() - startTime
console.log(arr)
console.log(useTime)


arr = []
startTime = performance.now()
for(let i = 0; i < len; i++) {
    arr = R.prepend(i, arr)
}
useTime = performance.now() - startTime
console.log(arr)
console.log(useTime)

arr = []
startTime = performance.now()
for(let i = 0; i < len; i++) {
    arr.splice(0, 0, i)
}
useTime = performance.now() - startTime
console.log(arr)
console.log(useTime)
</script>

測試中發現當數據量小於三百的時候,使用splice性能更好;小數據量的時候ramda的prepend方法性能也是最差的。測試

相關文章
相關標籤/搜索