My project has a requirement API to return an array(about 500 element struct)
I have tried to use lib like fasthttp
, easyjson
, rapidjson
(call with cgo
),but result is not good enough.
Do you guys have any better recommendation?
Here is my code:
type Line struct {
Time string `json:"time" bson:"time"`
Open float64 `json:"open" bson:"open"`
Close float64 `json:"close" bson:"close"`
High float64 `json:"high" bson:"high"`
Low float64 `json:"low" bson:"low"`
Volume float64 `json:"volume" bson:"volume"`
Amount float64 `json:"amount" bson:"amount"`
}
type MultiLines struct {
AllLines []Line `json:"lines"`
}
Test Code:
func BenchmarkJson500(b *testing.B) {
for i := 0; i < b.N; i++ {
_, err := json.Marshal(&sliceData)
if err != nil {
panic(err)
}
}
}
func BenchmarkUnmarshalJson500(b *testing.B) {
lines := make([]Line, 500)
for i := 0; i < b.N; i++ {
err := json.Unmarshal(sliceJson, &MultiLines{lines})
if err != nil {
panic(err)
}
}
}
func BenchmarkEasyJson500(b *testing.B) {
for i := 0; i < b.N; i++ {
_, err := sliceData.MarshalJSON()
if err != nil {
panic(err)
}
}
}
func BenchmarkEasyUnmarshalJson500(b *testing.B) {
for i := 0; i < b.N; i++ {
slice := MultiLines{}
err := slice.UnmarshalJSON(sliceJson)
if err != nil {
panic(err)
}
}
}
And benchmark tests result:
BenchmarkUnmarshalJson500-4 500 2821450 ns/op
BenchmarkJson500-4 500 2151984 ns/op
Because EasyJson Rewrite the UnmarshalJSON/MarshalJSON,so i test with the generated code at different time.
BenchmarkEasyJson500-4 1000 1434724 ns/op
BenchmarkEasyUnmarshalJson500-4 1000 1276298 ns/op
Anyway,ffjson is very similar with easyjson.