Merge pull request #2 from zeroZshadow/master

Fix UnmarshalJSON benchmark & Optimize MarshalJSON a little more
This commit is contained in:
Bruce 2016-06-10 21:24:27 -05:00 committed by GitHub
commit cd8e42350a
2 changed files with 7 additions and 6 deletions

View File

@ -127,7 +127,8 @@ func (f ID) Step() int64 {
// MarshalJSON returns a json byte array string of the snowflake ID. // MarshalJSON returns a json byte array string of the snowflake ID.
func (f ID) MarshalJSON() ([]byte, error) { func (f ID) MarshalJSON() ([]byte, error) {
buff := []byte("\"") buff := make([]byte, 0, 22)
buff = append(buff, '"')
buff = strconv.AppendInt(buff, int64(f), 10) buff = strconv.AppendInt(buff, int64(f), 10)
buff = append(buff, '"') buff = append(buff, '"')
return buff, nil return buff, nil

View File

@ -44,26 +44,26 @@ func BenchmarkGenerate(b *testing.B) {
} }
func BenchmarkUnmarshal(b *testing.B) { func BenchmarkUnmarshal(b *testing.B) {
// Generate the ID to unmarshal
node, _ := NewNode(1) node, _ := NewNode(1)
id := node.Generate() id := node.Generate()
bytes, _ := id.MarshalJSON()
var id2 ID var id2 ID
b.ReportAllocs() b.ReportAllocs()
b.ResetTimer() b.ResetTimer()
for n := 0; n < b.N; n++ { for n := 0; n < b.N; n++ {
_ = id2.UnmarshalJSON(id.Bytes()) _ = id2.UnmarshalJSON(bytes)
} }
} }
func BenchmarkMarshal(b *testing.B) { func BenchmarkMarshal(b *testing.B) {
// Generate the ID to marshal
node, _ := NewNode(1) node, _ := NewNode(1)
id := node.Generate() id := node.Generate()
b.ReportAllocs() b.ReportAllocs()
b.ResetTimer() b.ResetTimer()
for n := 0; n < b.N; n++ { for n := 0; n < b.N; n++ {
_, _ = id.MarshalJSON() _, _ = id.MarshalJSON()