Skip to content

Instantly share code, notes, and snippets.

@packrat386
Created June 27, 2016 14:14
Show Gist options
  • Save packrat386/874d5182b2083f05424c5750ba9df059 to your computer and use it in GitHub Desktop.
Save packrat386/874d5182b2083f05424c5750ba9df059 to your computer and use it in GitHub Desktop.
package benchtest
import (
"encoding/json"
"fmt"
"strconv"
"testing"
"time"
)
type TestStruct struct {
AnInt int `json:"an_int"`
AnotherInt int `json:"another_int"`
Str string `json:"string"`
Time time.Time `json:"time"`
Bool bool `json:"bool"`
}
var tester = TestStruct{
AnInt: 1,
AnotherInt: 2,
Str: "stringy",
Time: time.Now(),
Bool: false,
}
func (t *TestStruct) JSON() []byte {
return []byte(`{"an_int":"` + strconv.Itoa(t.AnInt) + `","another_int":"` + strconv.Itoa(t.AnotherInt) + `","string":"` + t.Str + `","time":"` + t.Time.String() + `","bool":"` + strconv.FormatBool(t.Bool) + `"}`)
}
const formatStr = `{"an_int":"%i","another_int":"%i","string":"%s","time":"%s","bool":"%t"}`
func (t *TestStruct) JSONFormat() []byte {
return []byte(fmt.Sprintf(formatStr, t.AnInt, t.AnotherInt, t.Str, t.Time.String(), t.Bool))
}
func BenchmarkJSONMarshal(b *testing.B) {
for n := 0; n < b.N; n++ {
json.Marshal(tester)
}
}
func BenchmarkJSON(b *testing.B) {
for n := 0; n < b.N; n++ {
tester.JSON()
}
}
func BenchmarkJSONFmt(b *testing.B) {
for n := 0; n < b.N; n++ {
tester.JSONFormat()
}
}
[fg-386] processor > go test -bench JSON -benchmem
PASS
BenchmarkJSONMarshal-8 1000000 1961 ns/op 568 B/op 6 allocs/op
BenchmarkJSON-8 2000000 752 ns/op 306 B/op 5 allocs/op
BenchmarkJSONFmt-8 1000000 1380 ns/op 392 B/op 8 allocs/op
ok git.enova.com/8b/amortizer/processor 5.665s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment