diff --git a/wsjson/wsjson_test.go b/wsjson/wsjson_test.go index a70e808cae326a536e96d067007ffeaadf9ef92e..080ab38dec9cafb81ad1c3d909b7d149461cc8a8 100644 --- a/wsjson/wsjson_test.go +++ b/wsjson/wsjson_test.go @@ -3,22 +3,51 @@ package wsjson_test import ( "encoding/json" "io" - "strings" + "strconv" "testing" + + "nhooyr.io/websocket/internal/test/xrand" ) func BenchmarkJSON(b *testing.B) { - msg := []byte(strings.Repeat("1234", 128)) - b.SetBytes(int64(len(msg))) - b.ReportAllocs() + sizes := []int{ + 8, + 16, + 32, + 128, + 256, + 512, + 1024, + 2048, + 4096, + 8192, + 16384, + } + b.Run("json.Encoder", func(b *testing.B) { - for i := 0; i < b.N; i++ { - json.NewEncoder(io.Discard).Encode(msg) + for _, size := range sizes { + b.Run(strconv.Itoa(size), func(b *testing.B) { + msg := xrand.String(size) + b.SetBytes(int64(size)) + b.ReportAllocs() + b.ResetTimer() + 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) + for _, size := range sizes { + b.Run(strconv.Itoa(size), func(b *testing.B) { + msg := xrand.String(size) + b.SetBytes(int64(size)) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + json.Marshal(msg) + } + }) } }) }