From f1a177422370ebbe97cdccc088ac7479700d18a1 Mon Sep 17 00:00:00 2001 From: xiezhengyao Date: Thu, 15 Aug 2024 17:51:21 +0800 Subject: [PATCH] optimize: free old buf --- bufiox/defaultbuf.go | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/bufiox/defaultbuf.go b/bufiox/defaultbuf.go index 0d34dae..1e1182f 100644 --- a/bufiox/defaultbuf.go +++ b/bufiox/defaultbuf.go @@ -27,10 +27,11 @@ const maxConsecutiveEmptyReads = 100 var _ Reader = &DefaultReader{} type DefaultReader struct { - buf []byte // buf[ri:] is the buffer for reading. - rd io.Reader // reader provided by the client - ri int // buf read positions - err error + buf []byte // buf[ri:] is the buffer for reading. + oldBuf [][]byte + rd io.Reader // reader provided by the client + ri int // buf read positions + err error maxSizeStats maxSizeStats @@ -97,6 +98,7 @@ func (r *DefaultReader) acquireSlow(n int) int { nbuf = dirtmake.Bytes(ncap, ncap) } else { nbuf = mcache.Malloc(ncap) + r.oldBuf = append(r.oldBuf, r.buf) } r.buf = nbuf[:copy(nbuf, r.buf)] } @@ -184,6 +186,12 @@ func (r *DefaultReader) Read(p []byte) (m int, err error) { } func (r *DefaultReader) Release(e error) error { + if !r.disableCache && r.oldBuf != nil { + for _, buf := range r.oldBuf { + mcache.Free(buf) + } + r.oldBuf = nil + } if len(r.buf)-r.ri == 0 { // release buf r.maxSizeStats.update(cap(r.buf)) @@ -330,6 +338,11 @@ func (w *DefaultWriter) Flush() (err error) { w.maxSizeStats.update(cap(w.buf)) if !w.disableCache { mcache.Free(w.buf) + if w.oldBuf != nil { + for _, buf := range w.oldBuf { + mcache.Free(buf) + } + } } w.buf = nil w.oldBuf = nil