Skip to content

Instantly share code, notes, and snippets.

@aktau
Created June 23, 2014 12:42
Show Gist options
  • Save aktau/b9dbcdfc2587c19ec7f6 to your computer and use it in GitHub Desktop.
Save aktau/b9dbcdfc2587c19ec7f6 to your computer and use it in GitHub Desktop.
golang: json (un)marshal benchmark
package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"testing"
)
type js struct {
I int64
D [64]byte
Name string
Tm string
M map[string]interface{}
Goop interface{}
}
func BenchmarkStreamEncode(b *testing.B) {
j := js{
M: map[string]interface{}{"key": 3, "bloo": "blaap"},
Goop: map[string]interface{}{"jeiajewa": 41, "jiqjweijqie": "iwjeqiejwqi"},
}
dec := json.NewEncoder(ioutil.Discard)
b.ResetTimer()
for i := 0; i < b.N; i++ {
dec.Encode(j)
}
}
func BenchmarkMarshal(b *testing.B) {
j := js{
M: map[string]interface{}{"key": 3, "bloo": "blaap"},
Goop: map[string]interface{}{"jeiajewa": 41, "jiqjweijqie": "iwjeqiejwqi"},
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
by, _ := json.Marshal(j)
ioutil.Discard.Write(by)
}
}
func BenchmarkMarshalNoWrite(b *testing.B) {
j := js{
M: map[string]interface{}{"key": 3, "bloo": "blaap"},
Goop: map[string]interface{}{"jeiajewa": 41, "jiqjweijqie": "iwjeqiejwqi"},
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
json.Marshal(j)
}
}
func BenchmarkStreamDecode(b *testing.B) {
j := js{
M: map[string]interface{}{"key": 3, "bloo": "blaap"},
Goop: map[string]interface{}{"jeiajewa": 41, "jiqjweijqie": "iwjeqiejwqi"},
}
by, _ := json.Marshal(j)
buf := bytes.NewBuffer(by)
dec := json.NewDecoder(buf)
var res js
b.ResetTimer()
for i := 0; i < b.N; i++ {
dec.Decode(&res)
buf.Write(by)
}
}
func BenchmarkBufferDecode(b *testing.B) {
j := js{
M: map[string]interface{}{"key": 3, "bloo": "blaap"},
Goop: map[string]interface{}{"jeiajewa": 41, "jiqjweijqie": "iwjeqiejwqi"},
}
by, _ := json.Marshal(j)
buf := bytes.NewReader(by)
dec := json.NewDecoder(buf)
var res js
b.ResetTimer()
for i := 0; i < b.N; i++ {
dec.Decode(&res)
buf.Seek(0, 0)
}
}
func BenchmarkUnmarshal(b *testing.B) {
j := js{
M: map[string]interface{}{"key": 3, "bloo": "blaap"},
Goop: map[string]interface{}{"jeiajewa": 41, "jiqjweijqie": "iwjeqiejwqi"},
}
by, _ := json.Marshal(j)
var res js
b.ResetTimer()
for i := 0; i < b.N; i++ {
json.Unmarshal(by, &res)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment