From d34e5d4b8e4c3d9ab9311d43492fe0bded560ccc Mon Sep 17 00:00:00 2001 From: Anmol Sethi Date: Fri, 20 Oct 2023 07:47:25 -0700 Subject: [PATCH] wsjson: Add json.Encoder vs json.Marshal benchmark json.Encoder is 42% faster than json.Marshal thanks to the memory reuse. goos: linux goarch: amd64 pkg: nhooyr.io/websocket/wsjson cpu: 12th Gen Intel(R) Core(TM) i5-1235U BenchmarkJSON/json.Encoder-12 3517579 340.2 ns/op 24 B/op 1 allocs/op BenchmarkJSON/json.Marshal-12 2374086 484.3 ns/op 728 B/op 2 allocs/op Closes #409 --- wsjson/wsjson_test.go | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 wsjson/wsjson_test.go diff --git a/wsjson/wsjson_test.go b/wsjson/wsjson_test.go new file mode 100644 index 00000000..a70e808c --- /dev/null +++ b/wsjson/wsjson_test.go @@ -0,0 +1,24 @@ +package wsjson_test + +import ( + "encoding/json" + "io" + "strings" + "testing" +) + +func BenchmarkJSON(b *testing.B) { + msg := []byte(strings.Repeat("1234", 128)) + b.SetBytes(int64(len(msg))) + b.ReportAllocs() + b.Run("json.Encoder", func(b *testing.B) { + for i := 0; i < b.N; i++ { + json.NewEncoder(io.Discard).Encode(msg) + } + }) + b.Run("json.Marshal", func(b *testing.B) { + for i := 0; i < b.N; i++ { + json.Marshal(msg) + } + }) +}