Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

reuse allocated buffer #271

Merged
merged 4 commits into from
Jul 6, 2021
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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) <= 128 {
// 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