This is an automated email from the ASF dual-hosted git repository.

wongoo pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/dubbo-go-hessian2.git


The following commit(s) were added to refs/heads/master by this push:
     new dad2892  reuse allocated buffer (#271)
dad2892 is described below

commit dad28924458a39d4b56e803f14e130b0156cae39
Author: tyltr <[email protected]>
AuthorDate: Tue Jul 6 08:43:17 2021 +0800

    reuse allocated buffer (#271)
    
    * reuse buffer  avoid allocate
    
    * reuse buffer clean
    
    * typo
    
    * reuse buf size 512
---
 encode.go | 18 ++++++++++++++++--
 1 file changed, 16 insertions(+), 2 deletions(-)

diff --git a/encode.go b/encode.go
index b6d9aed..cd3e11a 100644
--- a/encode.go
+++ b/encode.go
@@ -21,9 +21,7 @@ import (
        "reflect"
        "time"
        "unsafe"
-)
 
-import (
        perrors "github.com/pkg/errors"
 )
 
@@ -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[:]

Reply via email to