在前端项目对数组,map的拷贝,比较中,咱们每每会去用json.stringify、json.parse,那么这样作究竟好很差呢?
通过一系列测试,发现用这种方式的性能是比较差的,下面是实验结果前端
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 35json
咱们发现差距在四倍左右,当数组变大基本也维持在这个比例api
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测试