Skip to content

Instantly share code, notes, and snippets.

@ericchiang
Last active November 20, 2015 01:20
Show Gist options
  • Select an option

  • Save ericchiang/edcce6524f218a5fd36e to your computer and use it in GitHub Desktop.

Select an option

Save ericchiang/edcce6524f218a5fd36e to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"io"
"io/ioutil"
"strings"
"testing"
)
var data = `{"name":"eric"}`
type Person struct {
Name string
}
func newReader() io.Reader {
return strings.NewReader(data)
}
func BenchmarkReadFirst(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
var p Person
data, err := ioutil.ReadAll(newReader())
if err != nil {
b.Fatal(err)
}
if err := json.Unmarshal(data, &p); err != nil {
b.Fatal(err)
}
}
}
func BenchmarkDecoder(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
var p Person
if err := json.NewDecoder(newReader()).Decode(&p); err != nil {
b.Fatal(err)
}
}
}
$ go test -bench=.
testing: warning: no tests to run
PASS
BenchmarkReadFirst-4 500000 2352 ns/op 2368 B/op 7 allocs/op
BenchmarkDecoder-4 1000000 1667 ns/op 1024 B/op 7 allocs/op
ok _/home/eric/p/go/json 2.892s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment