本日闲着无聊测试了一下js数组splice要领的机能发明:当数组的长度大于100000的时刻全部页面会出于比较长的卡死状况,故试着写了个机能更好的要领来完成批量在数组头部插进去数据:
let splice = function (arr) {
let cache = arr || []
return {
add: function (value) {
cache.push(value)
},
get: function () {
return cache.reverse()
}
}
}
和ramda、原生splice的机能比较:
测试代码以下:
<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要领机能也是最差的。