Skip to content

Instantly share code, notes, and snippets.

@mmcloughlin
Last active November 1, 2017 22:56
Show Gist options
  • Select an option

  • Save mmcloughlin/76b1da1025c5e28aefe20e311c84dd3e to your computer and use it in GitHub Desktop.

Select an option

Save mmcloughlin/76b1da1025c5e28aefe20e311c84dd3e to your computer and use it in GitHub Desktop.
Mapstructure benchmark

Basic mapstructure benchmark against plain assignment.

=== RUN   TestDecodeMapStructure
--- PASS: TestDecodeMapStructure (0.00s)
=== RUN   TestDecodePlain
--- PASS: TestDecodePlain (0.00s)
goos: darwin
goarch: amd64
pkg: github.com/mmcloughlin/mapstructurebench
BenchmarkDecodeMapStructure-4   	 1000000	      2223 ns/op
BenchmarkDecodePlain-4          	100000000	        19.8 ns/op
PASS
ok  	github.com/mmcloughlin/mapstructurebench	4.263s
package mapstructurebench
import (
"errors"
"github.com/mitchellh/mapstructure"
)
type X struct {
A int `mapstructure:"a"`
B int `mapstructure:"b"`
}
func DecodeMapStructure(v map[string]interface{}, x *X) error {
return mapstructure.Decode(v, x)
}
func DecodePlain(v map[string]interface{}, x *X) error {
ai, ok := v["a"]
if !ok {
return errors.New("missing field")
}
a, ok := ai.(int)
if !ok {
return errors.New("failed cast")
}
x.A = a
bi, ok := v["b"]
if !ok {
return errors.New("missing field")
}
b, ok := bi.(int)
if !ok {
return errors.New("failed cast")
}
x.B = b
return nil
}
package mapstructurebench
import (
"testing"
"github.com/stretchr/testify/assert"
)
type Decoder func(map[string]interface{}, *X) error
func VerifyDecoder(t *testing.T, d Decoder) {
x := &X{}
v := map[string]interface{}{
"a": 1,
"b": 2,
}
d(v, x)
assert.Equal(t, 1, x.A)
assert.Equal(t, 2, x.B)
}
func TestDecodeMapStructure(t *testing.T) {
VerifyDecoder(t, DecodeMapStructure)
}
func TestDecodePlain(t *testing.T) {
VerifyDecoder(t, DecodePlain)
}
func BenchDecoder(b *testing.B, d Decoder) {
x := &X{}
v := map[string]interface{}{
"a": 1,
"b": 2,
}
for i := 0; i < b.N; i++ {
d(v, x)
}
}
func BenchmarkDecodeMapStructure(b *testing.B) {
BenchDecoder(b, DecodeMapStructure)
}
func BenchmarkDecodePlain(b *testing.B) {
BenchDecoder(b, DecodePlain)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment