Skip to content

Commit

Permalink
feat: add Writer pool
Browse files Browse the repository at this point in the history
  • Loading branch information
tdakkota committed Jan 20, 2022
1 parent 4f7480a commit 5c19f2c
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 5 deletions.
16 changes: 16 additions & 0 deletions jx.go
Expand Up @@ -19,6 +19,11 @@ var (
return &Encoder{}
},
}
writerPool = &sync.Pool{
New: func() interface{} {
return &Writer{}
},
}
decPool = &sync.Pool{
New: func() interface{} {
return &Decoder{}
Expand Down Expand Up @@ -48,3 +53,14 @@ func PutEncoder(e *Encoder) {
e.SetIdent(0)
encPool.Put(e)
}

// GetWriter returns *Writer from pool.
func GetWriter() *Writer {
return writerPool.Get().(*Writer)
}

// PutWriter puts *Writer to pool
func PutWriter(e *Writer) {
e.Reset()
writerPool.Put(e)
}
9 changes: 6 additions & 3 deletions otel_test.go
Expand Up @@ -327,14 +327,17 @@ func BenchmarkOTEL(b *testing.B) {
}
})
b.Run("Write", func(b *testing.B) {
w := GetWriter()
defer PutWriter(w)
v.Write(w)

b.ReportAllocs()
var w Writer
v.Write(&w)
b.SetBytes(int64(len(w.Buf)))
b.ResetTimer()

for i := 0; i < b.N; i++ {
w.Reset()
v.Write(&w)
v.Write(w)
}
})
b.Run("Encode", func(b *testing.B) {
Expand Down
6 changes: 4 additions & 2 deletions w_test.go
Expand Up @@ -7,14 +7,16 @@ import (
)

func TestWriter_Reset(t *testing.T) {
var w Writer
w := GetWriter()
defer PutWriter(w)
w.True()
require.NotEmpty(t, w.Buf)
w.Reset()
require.Empty(t, w.Buf)
}

func TestWriter_String(t *testing.T) {
w := Writer{Buf: []byte(`true`)}
w := GetWriter()
defer PutWriter(w)
require.Equal(t, "true", w.String())
}

0 comments on commit 5c19f2c

Please sign in to comment.