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 4a81f2a
Showing 1 changed file with 32 additions and 12 deletions.
44 changes: 32 additions & 12 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,18 +186,31 @@ func (r *DefaultReader) Read(p []byte) (m int, err error) {
}

func (r *DefaultReader) Release(e error) error {
if len(r.buf)-r.ri == 0 {
// release buf
r.maxSizeStats.update(cap(r.buf))
if !r.disableCache {
if !r.disableCache {
if 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))
mcache.Free(r.buf)
r.buf = nil
r.ri = 0
} else {
n := copy(r.buf, r.buf[r.ri:])
r.buf = r.buf[:n]
r.ri = 0
}
r.buf = nil
} else {
n := copy(r.buf, r.buf[r.ri:])
r.buf = r.buf[:n]
r.oldBuf = nil
if len(r.buf)-r.ri == 0 {
r.buf = nil
r.ri = 0
}
}
r.ri = 0
return nil
}

Expand Down Expand Up @@ -330,6 +345,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 4a81f2a

Please sign in to comment.