Skip to content

Instantly share code, notes, and snippets.

@tidwall
Last active April 19, 2022 22:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tidwall/4bba4ee9473f810371046b8564d45e9d to your computer and use it in GitHub Desktop.
Save tidwall/4bba4ee9473f810371046b8564d45e9d to your computer and use it in GitHub Desktop.
Benchmark encoding json strings in Go (gjson, jsoniter, encoding/json)
package main
import (
"encoding/json"
"testing"
jsoniter "github.com/json-iterator/go"
"github.com/tidwall/gjson"
)
var inputs = []string{
`""`,
`"ascii"`,
`"ascii with \n line break"`,
`"emoji KO \ud83d\udd13, \ud83c\udfc3 OK \u2764\ufe0f"`,
`"extended 的情况下解"`,
`"control \u0000"`,
`"escapes \t\r\n >><<"`,
`"_\ufffd\u000b\ufffd\ufffd|X!\ufffd\ufffdU\u0026\ufffd\u001a\ufffd\u0004"`,
}
var simple = `"hello world"`
func BenchmarkJSONString_GJSON_Simple(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = string(gjson.AppendJSONString(nil, simple))
}
}
func BenchmarkJSONString_GJSON_Extended(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = string(gjson.AppendJSONString(nil, inputs[i&(len(inputs)-1)]))
}
}
func BenchmarkJSONString_GO_Simple(b *testing.B) {
bsimple := []byte(simple)
b.ResetTimer()
for i := 0; i < b.N; i++ {
var s string
json.Unmarshal(bsimple, &s)
}
}
func BenchmarkJSONString_GO_Extended(b *testing.B) {
binputs := make([][]byte, len(inputs))
for i := 0; i < len(inputs); i++ {
binputs[i] = []byte(inputs[i])
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
var s string
json.Unmarshal(binputs[i&(len(inputs)-1)], &s)
}
}
func BenchmarkJSONString_JSONIter_Simple(b *testing.B) {
bsimple := []byte(simple)
b.ResetTimer()
for i := 0; i < b.N; i++ {
var s string
jsoniter.Unmarshal(bsimple, &s)
}
}
func BenchmarkJSONString_JSONIter_Extended(b *testing.B) {
binputs := make([][]byte, len(inputs))
for i := 0; i < len(inputs); i++ {
binputs[i] = []byte(inputs[i])
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
var s string
jsoniter.Unmarshal(binputs[i&(len(inputs)-1)], &s)
}
}
@tidwall
Copy link
Author

tidwall commented Apr 19, 2022

go test -bench .
goos: darwin
goarch: arm64
pkg: github.com/tidwall/gjson/main
BenchmarkJSONString_GJSON_Simple-10         	18116595	        66.20 ns/op
BenchmarkJSONString_GJSON_Extended-10       	10743160	       111.5 ns/op
BenchmarkJSONString_GO_Simple-10            	 8227428	       141.4 ns/op
BenchmarkJSONString_GO_Extended-10          	 5182388	       233.5 ns/op
BenchmarkJSONString_JSONIter_Simple-10      	16021922	        73.91 ns/op
BenchmarkJSONString_JSONIter_Extended-10    	 7400431	       162.4 ns/op

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment