Skip to content

Instantly share code, notes, and snippets.

@dgrr
Created July 20, 2021 08:31
Directly using Frame.Payload to encode data against using an intermediate buffer.
package main
import (
"bytes"
"testing"
"github.com/dgrr/websocket"
"github.com/valyala/bytebufferpool"
"github.com/valyala/fastjson"
)
func getObject() *fastjson.Value {
ar := fastjson.Arena{}
v := ar.NewObject()
inner := ar.NewObject()
inner.Set("z", ar.NewString("inner object"))
v.Set("a", ar.NewNumberInt(20))
v.Set("b", ar.NewString("hello world"))
v.Set("c", inner)
return v
}
func BenchmarkWithByteBuffer(b *testing.B) {
v := getObject()
for i := 0; i < b.N; i++ {
bf := bytebufferpool.Get()
bf.B = v.MarshalTo(bf.B[:0])
fr := websocket.AcquireFrame()
fr.SetPayload(bf.B)
if !bytes.Equal(fr.Payload(), []byte(`{"a":20,"b":"hello world","c":{"z":"inner object"}}`)) {
b.Fatal("unequal")
}
bytebufferpool.Put(bf)
websocket.ReleaseFrame(fr)
}
}
func BenchmarkWithoutByteBuffer(b *testing.B) {
v := getObject()
for i := 0; i < b.N; i++ {
fr := websocket.AcquireFrame()
fr.SetPayload(
v.MarshalTo(fr.Payload()))
if !bytes.Equal(fr.Payload(), []byte(`{"a":20,"b":"hello world","c":{"z":"inner object"}}`)) {
b.Fatal("unequal")
}
websocket.ReleaseFrame(fr)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment