Skip to content

Commit

Permalink
reuse allocated buffer (#271)
Browse files Browse the repository at this point in the history
* reuse buffer  avoid allocate

* reuse buffer clean

* typo

* reuse buf size 512
  • Loading branch information
tylitianrui committed Jul 6, 2021
1 parent 2a66988 commit 0f35834
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,7 @@ import (
"reflect"
"time"
"unsafe"
)

import (
perrors "github.com/pkg/errors"
)

Expand Down Expand Up @@ -56,6 +54,22 @@ func (e *Encoder) Clean() {
e.refMap = make(map[unsafe.Pointer]_refElem, 7)
}

// ReuseBufferClean reuse the Encoder for a new object encoding.
// it reuse allocated buffer and reduce memory-allocation.
func (e *Encoder) ReuseBufferClean() {
var buffer []byte
if cap(e.buffer) <= 512 {
// reuse buffer, avoid allocate
buffer = e.buffer[:0]
} else {
// avoiding memory leak caused by growth of underlying array
buffer = make([]byte, 64)
}
e.classInfoList = nil
e.buffer = buffer[:0]
e.refMap = make(map[unsafe.Pointer]_refElem, 7)
}

// Buffer returns byte buffer
func (e *Encoder) Buffer() []byte {
return e.buffer[:]
Expand Down

0 comments on commit 0f35834

Please sign in to comment.