Created
July 16, 2018 04:15
-
-
Save cloverstd/3b95c43c27d8ef93d0b5a8f9224b0517 to your computer and use it in GitHub Desktop.
benchmark with json
This file contains 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_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