在前端项目对数组,map的拷贝,比较中,我们每每会去用json.stringify、json.parse,那末如许做终究好不好呢?
经由一系列测试,发明用这类体式格局的机能是比较差的,下面是试验效果
1.数组拷贝
const a1 = new Array(1000000).fill('').map((e, index) => index)
function f1() {
const start = new Date().getTime()
const r = JSON.parse(JSON.stringify(a1))
console.log('json效果', new Date().getTime() - start)
}
function f2() {
const start = new Date().getTime()
const r = [...a1]
console.log('array效果', r == a1, new Date().getTime() - start)
}
f1()
f2()
效果:
json效果 104
array效果 false 35
我们发明差异在四倍摆布,当数组变大基础也维持在这个比例
2.遍历对照
const map1 = {}
const map2 = {}
for (let i=0;i < 1000000;i++) {
map1[i] = i
map2[i] = i
}
function f1() {
const start = new Date().getTime()
const r = JSON.stringify(map1) == JSON.stringify(map2)
console.log('json效果', r, new Date().getTime() - start)
}
function f2() {
const start = new Date().getTime()
const r = Object.keys(map1).every(key => {
if (map2[key] || map2[key] === 0) {
return true
} else {
return false
}
})
console.log('array效果', r, new Date().getTime() - start)
}
f1()
f2()
效果:
json效果 true 506
array效果 true 140
基础上也是在四倍摆布的差异
末端
另有更多的测试没做,但预计基础上也是这个差异,
实在说到底,用json的api底层也是遍历过了,而且转成字符串,所以机能会比较差
人人照样本身手写的遍历照样手写,或许用第三方插件如lodash。不要一味用json api