Skip to content

Commit

Permalink
Merge pull request #31 from tdakkota/feat/add-writer-pool
Browse files Browse the repository at this point in the history
feat: add Writer pool
  • Loading branch information
ernado committed Jan 20, 2022
2 parents 4f7480a + 05e5dca commit c929480
Show file tree
Hide file tree
Showing 3 changed files with 29 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
9 changes: 7 additions & 2 deletions w_test.go
Expand Up @@ -7,14 +7,19 @@ 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)

w.True()
require.Equal(t, "true", w.String())
}

0 comments on commit c929480

Please sign in to comment.