Skip to content

Commit

Permalink
optimize: free old buf
Browse files Browse the repository at this point in the history
  • Loading branch information
jayantxie committed Aug 15, 2024
1 parent dc05df6 commit f1a1774
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions bufiox/defaultbuf.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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)]
}
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit f1a1774

Please sign in to comment.