前端关于JSON的stringifyparse和遍历的性能比较

7次阅读

共计 1026 个字符,预计需要花费 3 分钟才能阅读完成。

在前端项目对数组,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

正文完
 0