Skip to content

Commit d34e5d4

Browse files
committed
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
1 parent ecf7dec commit d34e5d4

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

wsjson/wsjson_test.go

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package wsjson_test
2+
3+
import (
4+
"encoding/json"
5+
"io"
6+
"strings"
7+
"testing"
8+
)
9+
10+
func BenchmarkJSON(b *testing.B) {
11+
msg := []byte(strings.Repeat("1234", 128))
12+
b.SetBytes(int64(len(msg)))
13+
b.ReportAllocs()
14+
b.Run("json.Encoder", func(b *testing.B) {
15+
for i := 0; i < b.N; i++ {
16+
json.NewEncoder(io.Discard).Encode(msg)
17+
}
18+
})
19+
b.Run("json.Marshal", func(b *testing.B) {
20+
for i := 0; i < b.N; i++ {
21+
json.Marshal(msg)
22+
}
23+
})
24+
}

0 commit comments

Comments
 (0)