Skip to content

Commit

Permalink
wsjson: Add json.Encoder vs json.Marshal benchmark
Browse files Browse the repository at this point in the history
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
  • Loading branch information
nhooyr committed Oct 26, 2023
1 parent ecf7dec commit d34e5d4
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions wsjson/wsjson_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}

0 comments on commit d34e5d4

Please sign in to comment.