Last active
April 19, 2022 22:23
-
-
Save tidwall/4bba4ee9473f810371046b8564d45e9d to your computer and use it in GitHub Desktop.
Benchmark encoding json strings in Go (gjson, jsoniter, encoding/json)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Author
tidwall
commented
Apr 19, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment