Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
benchmark with json
package main_test
import (
"encoding/json"
"testing"
)
func BenchmarkJSONMarshalStruct(b *testing.B) {
type Foo struct {
Name string `json:"name"`
Int int `json:"int"`
Bool bool `json:"bool"`
Byte []byte `json:"byte"`
}
foo := Foo{
Name: "name",
Int: 10,
Bool: false,
Byte: []byte("1234"),
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
json.Marshal(foo)
}
}
func BenchmarkJSONMarshalMap(b *testing.B) {
foo := map[string]interface{}{
"name": "name",
"int": 10,
"bool": false,
"byte": []byte("1234"),
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
json.Marshal(foo)
}
}
func BenchmarkJSONMarshalMapSameType(b *testing.B) {
foo := map[string]int{
"int1": 1,
"int2": 2,
"int3": 3,
"int4": 4,
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
json.Marshal(foo)
}
}
func BenchmarkJSONMarshalStructSameType(b *testing.B) {
type Foo struct {
Int1 int `json:"int1"`
Int2 int `json:"int2"`
Int3 int `json:"int3"`
Int4 int `json:"int4"`
}
foo := Foo{
Int1: 1,
Int2: 2,
Int3: 3,
Int4: 4,
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
json.Marshal(foo)
}
}
func BenchmarkJSONMarshalMapEmbed(b *testing.B) {
foo := map[string]interface{}{
"name": "name",
"int": 10,
"bool": false,
"byte": []byte("1234"),
"foo": map[string]interface{}{
"name": "name",
"int": 10,
"bool": false,
"byte": []byte("1234"),
"foo": map[string]interface{}{
"name": "name",
"int": 10,
"bool": false,
"byte": []byte("1234"),
},
},
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
json.Marshal(foo)
}
}
func BenchmarkJSONMarshalStructEmbed(b *testing.B) {
type Foo struct {
Name string `json:"name"`
Int int `json:"int"`
Bool bool `json:"bool"`
Byte []byte `json:"byte"`
Foo *Foo `json:"foo"`
}
foo := Foo{
Name: "name",
Int: 10,
Bool: false,
Byte: []byte("1234"),
Foo: &Foo{
Name: "name",
Int: 10,
Bool: false,
Byte: []byte("1234"),
Foo: &Foo{
Name: "name",
Int: 10,
Bool: false,
Byte: []byte("1234"),
},
},
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
json.Marshal(foo)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.