From bb0fb2c0f5f41c98973658c2bec13b451571ac47 Mon Sep 17 00:00:00 2001 From: zeroZshadow Date: Sat, 11 Jun 2016 03:48:54 +0200 Subject: [PATCH 1/2] Fix UnmarshalJSON benchmark Optimize MarshalJSON a little more --- snowflake.go | 3 ++- snowflake_test.go | 10 +++++----- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/snowflake.go b/snowflake.go index 21cc5e8..c857378 100644 --- a/snowflake.go +++ b/snowflake.go @@ -127,7 +127,8 @@ func (f ID) Step() int64 { // MarshalJSON returns a json byte array string of the snowflake ID. func (f ID) MarshalJSON() ([]byte, error) { - buff := []byte("\"") + buff := make([]byte, 0, 2) + buff = append(buff, '"') buff = strconv.AppendInt(buff, int64(f), 10) buff = append(buff, '"') return buff, nil diff --git a/snowflake_test.go b/snowflake_test.go index 93c459e..40c1a95 100644 --- a/snowflake_test.go +++ b/snowflake_test.go @@ -44,26 +44,26 @@ func BenchmarkGenerate(b *testing.B) { } func BenchmarkUnmarshal(b *testing.B) { - + // Generate the ID to unmarshal node, _ := NewNode(1) id := node.Generate() + bytes, _ := id.MarshalJSON() + var id2 ID b.ReportAllocs() - b.ResetTimer() for n := 0; n < b.N; n++ { - _ = id2.UnmarshalJSON(id.Bytes()) + _ = id2.UnmarshalJSON(bytes) } } func BenchmarkMarshal(b *testing.B) { - + // Generate the ID to marshal node, _ := NewNode(1) id := node.Generate() b.ReportAllocs() - b.ResetTimer() for n := 0; n < b.N; n++ { _, _ = id.MarshalJSON() From 8abf09e1ce3fbe8a4a7edae53b3aebca7aa95838 Mon Sep 17 00:00:00 2001 From: zeroZshadow Date: Sat, 11 Jun 2016 04:20:04 +0200 Subject: [PATCH 2/2] Allocate the maximum in 1 go for marshaling --- snowflake.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snowflake.go b/snowflake.go index c857378..26da1fe 100644 --- a/snowflake.go +++ b/snowflake.go @@ -127,7 +127,7 @@ func (f ID) Step() int64 { // MarshalJSON returns a json byte array string of the snowflake ID. func (f ID) MarshalJSON() ([]byte, error) { - buff := make([]byte, 0, 2) + buff := make([]byte, 0, 22) buff = append(buff, '"') buff = strconv.AppendInt(buff, int64(f), 10) buff = append(buff, '"')