性能测试之Json处理

Golang Json解析性能对比

  • 测试平台: M1 Macbook Pro
  • golang版本: 1.18.3

测试代码

package json_marshal

import (
	"encoding/json"
	"testing"

	go_json "github.com/goccy/go-json"
	jsoniter "github.com/json-iterator/go"
)

var data = `{
"a":"a",
"b":1,
"c":true,
"d":{"text":1,"text1":"text"}
}`

type Tmp struct {
	A string                 `json:"a"`
	B int                    `json:"b"`
	C bool                   `json:"c"`
	D map[string]interface{} `json:"d"`
}

func BenchmarkUseEncodingJson(b *testing.B) {
	for n := 0; n < b.N; n++ {
		var t Tmp
		_ = json.Unmarshal([]byte(data), &t)
	}
}

func BenchmarkUseJsoniter(b *testing.B) {
	for n := 0; n < b.N; n++ {
		var t Tmp
		_ = jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal([]byte(data), &t)
	}
}

func BenchmarkUseGoJson(b *testing.B) {
	for n := 0; n < b.N; n++ {
		var t Tmp
		_ = go_json.Unmarshal([]byte(data), &t)
	}
}

测试结果

go test -bench=. -benchmem -run=none

goos: darwin
goarch: arm64
pkg: golang_benchmark/json_marshal
BenchmarkUseEncodingJson-8        952381               1218 ns/op            816 B/op         19 allocs/op
BenchmarkUseJsoniter-8           2642527               453.6 ns/op           560 B/op         14 allocs/op
BenchmarkUseGoJson-8             3316332               362.3 ns/op           600 B/op         11 allocs/op
PASS
ok      golang_benchmark/json_marshal   5.394s

测试结论

  • 目前为止go_json包的性能最优
  • gin目前已经支持Jsoniter与go_json作为默认的json解析工具,编译时至于添加tag指定解析器即可
更新于