之前看到过json-iterator库使用,为何替换掉原生的json呢,看了一下github,如下:
json-iterator is a high-performance 100% compatible drop-in replacement of "encoding/json"
因为其高性能而为广泛使用,今天测试一个场景,假设有个数组["aaaa", "bbb" .....] 里面存储的全是字符串,字符串长度姑且定位10吧,从字符串Unmarshal为slice string后,采用原生json与json-iter的对比,后面称呼json-iter为jsoniter吧。
jsoniter地址如下:
https://github.com/json-iterator/go
json
goos: linux
goarch: amd64
cpu: AMD EPYC 7K62 48-Core Processor
BenchmarkJson
BenchmarkJson-8 171060 7230 ns/op 1161 B/op 22 allocs/op
PASS
jsoniter
goos: linux
goarch: amd64
cpu: AMD EPYC 7K62 48-Core Processor
BenchmarkJsonIter
BenchmarkJsonIter-8 443746 2921 ns/op 1011 B/op 24 allocs/op
PASS
json
goos: linux
goarch: amd64
cpu: AMD EPYC 7K62 48-Core Processor
BenchmarkJson
BenchmarkJson-8 2842 426381 ns/op 88175 B/op 1036 allocs/op
PASS
jsoniter
goos: linux
goarch: amd64
cpu: AMD EPYC 7K62 48-Core Processor
BenchmarkJsonIter
BenchmarkJsonIter-8 10000 122974 ns/op 65640 B/op 1026 allocs/op
PASS
json
goos: linux
goarch: amd64
cpu: AMD EPYC 7K62 48-Core Processor
BenchmarkJson
BenchmarkJson-8 26 43026436 ns/op 10597790 B/op 100260 allocs/op
jsoniter
goos: linux
goarch: amd64
cpu: AMD EPYC 7K62 48-Core Processor
BenchmarkJsonIter
BenchmarkJsonIter-8 75 16120198 ns/op 12341738 B/op 100141 allocs/op
PASS
我们可以看到jsoniter确实比json有这不错的性能优势,从ns/op这个数据看到原生jsoniter是3-4倍的jsoniter,但是从allocs/op上来看效果差距不大。所以针对内存开销比较大的场景,还是适合使用缓存解决,当然缓存存在更新、过期的问题,如果数据长久不变,使用缓存将是不错的选择,如果数据变动非常频繁,那么只能动态的来计算。