推薦一個Json解析庫

gofish發表於2019-02-18

推薦一個json庫 gojson,可以通過命令列工具根據輸入的Struct動態生成MarshalJSON/UnmarshalJSON方法,效能與EasyJSON、Jsonparser、Jsoniter相比要好很多

GoJSON

GoJSON is a fast and easy package to marshal/unmarshal struct to/from json. You can use GoJSON tool to generate marshal/unmarshal code, in benchmark tests, GoJSON's generate code is almost 6~7 times faster than encoding/json.

Example

# install
  go get -u -v github.com/go-fish/gojson
  cd ${GOPATH}/src/github.com/go-fish/gojson/cmd
  go build -o gojson main.go

# usage
  gojson [options] <input dir|file>

  -inline
        Use inline function in generate code (default true)
  -m string
        Mode of generate, eg: encode, decode, all (default "all")
  -o string
        Optional name of the output file to be generated. (default "gojson.generate.go")
  -unsafe
        Use decoder without copy data
  -version
        Show version information.

with -inline && -unsafe, you can get most performance generate code with -m, gojson will generate marshal/unmarshal/both for all expose structs in input dir/file.

For expose structs, gojson generate MarshalJSON/UnmarshalJSON methods for marshal/unmarshal json. You also can use gojson.Marshal/gojson.Unmarshal functions to marshal/unmarshal json.

Benchmark

Large Payload

Unmarshal

gojson 114658 ns/op 457.72 MB/s 5873 B/op 253 allocs/op
jsonparser 116647 ns/op 449.92 MB/s 0 B/op 0 allocs/op
easyjson 219673 ns/op 238.91 MB/s 9264 B/op 349 allocs/op
gojay 92398 ns/op 567.99 MB/s 5985 B/op 259 allocs/op
jsoniter 159877 ns/op 328.26 MB/s 800 B/op 29 allocs/op
encoding/json 680867 ns/op 377.08 MB/s 6154 B/op 258 allocs/op

Marshal

gojson 131 ns/op 400511.56 MB/s 32 B/op 1 allocs/op
easyjson 235 ns/op 223039.53 MB/s 272 B/op 3 allocs/op
encoding/json 597 ns/op 87819.16 MB/s 120 B/op 4 allocs/op

Medium Payload

Unmarshal

gojson 4056 ns/op 510.51 MB/s 240 B/op 10 allocs/op
jsonparser 9379 ns/op 220.81 MB/s 0 B/op 0 allocs/op
easyjson 8107 ns/op 255.43 MB/s 288 B/op 11 allocs/op
gojay 5004 ns/op 413.84 MB/s 2472 B/op 10 allocs/op
jsoniter 10579 ns/op 195.75 MB/s 2576 B/op 12 allocs/op
encoding/json 28030 ns/op 73.88 MB/s 520 B/op 15 allocs/op

Marshal

gojson 105 ns/op 19551.00 MB/s 32 B/op 1 allocs/op
easyjson 193 ns/op 10700.99 MB/s 272 B/op 3 allocs/op
encoding/json 443 ns/op 4667.11 MB/s 120 B/op 4 allocs/op

Small Payload

Unmarshal

gojson 812 ns/op 176.00 MB/s 160 B/op 5 allocs/op
jsonparser 925 ns/op 154.47 MB/s 0 B/op 0 allocs/op
easyjson 1209 ns/op 118.26 MB/s 128 B/op 8 allocs/op
gojay 977 ns/op 146.30 MB/s 304 B/op 6 allocs/op
jsoniter 1847 ns/op 77.42 MB/s 336 B/op 7 allocs/op
encoding/json 2576 ns/op 55.49 MB/s 328 B/op 7 allocs/op

Marshal

gojson 331 ns/op 431.90 MB/s 32 B/op 1 allocs/op
easyjson 439 ns/op 325.35 MB/s 272 B/op 3 allocs/op
encoding/json 1398 ns/op 102.22 MB/s 120 B/op 4 allocs/op

Questions

Any questions or bugs can go though github issues.

相關文章