Skip to content

Commit aecdebb

Browse files
committed
cache allocated buffer
1 parent 7019692 commit aecdebb

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

buffer.go

+11-6
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import (
66
)
77

88
const defaultBufSize = 4096 // must be 2^n
9-
// const maxCachedBufSize = 256 * 1024
9+
const maxCachedBufSize = 256 * 1024
1010

1111
type writeBuffer struct {
1212
buf []byte
@@ -39,9 +39,10 @@ func (wb *writeBuffer) store(buf []byte) {
3939
}
4040

4141
type readBuffer struct {
42-
buf []byte
43-
idx int
44-
nc net.Conn
42+
buf []byte
43+
idx int
44+
nc net.Conn
45+
cached []byte
4546
}
4647

4748
func newReadBuffer(nc net.Conn) readBuffer {
@@ -54,12 +55,16 @@ func newReadBuffer(nc net.Conn) readBuffer {
5455
// fill reads into the buffer until at least _need_ bytes are in it.
5556
func (rb *readBuffer) fill(need int) error {
5657
var buf []byte
57-
if need <= cap(rb.buf) {
58-
buf = rb.buf[:0]
58+
if need <= cap(rb.cached) {
59+
buf = rb.cached[:0]
5960
} else {
6061
// Round up to the next multiple of the default size
6162
size := (need + defaultBufSize - 1) &^ (defaultBufSize - 1)
63+
6264
buf = make([]byte, 0, size)
65+
if size <= maxCachedBufSize {
66+
rb.cached = buf
67+
}
6368
}
6469

6570
// move the existing data to the start of it.

0 commit comments

Comments
 (0)