Last active
November 20, 2015 01:20
-
-
Save ericchiang/edcce6524f218a5fd36e to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
| 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) | |
| } | |
| } | |
| } |
This file contains hidden or 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
| $ 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