Skip to content

Instantly share code, notes, and snippets.

@graphaelli
Created March 27, 2018 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save graphaelli/8d1dc73827d7133c00e58202a024eedc to your computer and use it in GitHub Desktop.
Save graphaelli/8d1dc73827d7133c00e58202a024eedc to your computer and use it in GitHub Desktop.
useNumber benchmark
package main
import (
"bytes"
"encoding/json"
"testing"
)
var (
data map[string]interface{}
)
func decodeFunc(useNumber bool) func(input []byte, dst interface{}) error {
return func(input []byte, dst interface{}) error {
d := json.NewDecoder(bytes.NewReader(input))
if useNumber {
d.UseNumber()
}
return d.Decode(dst)
}
}
func TestDecodeIntDefault(t *testing.T) {
decode := decodeFunc(false)
decode([]byte(`{"a": 10000000}`), &data)
if v, ok := data["a"].(float64); !ok {
t.Error("expected float64 type assertion with useNumber")
} else {
if v != 10000000 {
t.Errorf("wanted: 10000000, got: %f %s", v)
}
}
}
func TestDecodeIntUseNumber(t *testing.T) {
decode := decodeFunc(true)
decode([]byte(`{"a": 10000000}`), &data)
if v, ok := data["a"].(json.Number); !ok {
t.Error("expected json.Number type assertion with useNumber")
} else {
if f, err := v.Int64(); err != nil || f != 10000000 {
t.Errorf("wanted: 10000000, got: %f %s", f, err)
}
}
}
func TestDecodeFloatDefault(t *testing.T) {
decode := decodeFunc(false)
decode([]byte(`{"a": 1.0}`), &data)
if v, ok := data["a"].(float64); !ok {
t.Error("expected float64 type assertion with useNumber")
} else {
if v != 1.0 {
t.Errorf("wanted: 1.0, got: %f %s", v)
}
}
}
func TestDecodeFloatUseNumber(t *testing.T) {
decode := decodeFunc(true)
decode([]byte(`{"a": 1.0}`), &data)
if v, ok := data["a"].(json.Number); !ok {
t.Error("expected json.Number type assertion with useNumber")
} else {
if f, err := v.Float64(); err != nil || f != 1.0 {
t.Errorf("wanted: 1.0, got: %f %s", f, err)
}
}
}
func BenchmarkDecode(b *testing.B) {
benchmarks := []struct {
name string
input []byte
}{
{"empty", []byte(`{}`)},
{"strings", []byte(`{"a": "b"}`)},
{"int", []byte(`{"a": 1}`)},
{"float", []byte(`{"a": 1.0}`)},
}
for _, bm := range benchmarks {
for d := 0; d <= 1; d++ {
useNumber := d == 1
decode := decodeFunc(useNumber)
suffix := "Default"
if useNumber {
suffix = "UseNumber"
}
b.Run(bm.name+suffix, func(b *testing.B) {
for i := 0; i < b.N; i++ {
decode(bm.input, &data)
}
})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment