Skip to content

Commit 195c88b

Browse files
Jorropogopherbot
authored andcommitted
net/http: use pointers to array for copyBufPool
This is inspired by CL 539915, I'm only submitting now that CL 456435 has been merged. This divide the number of objects kept alive by the heap by two and remove the slice header allocation in New and in the put back. Change-Id: Ibcd5166bac5a37f365a533e09a28f3b79f81ad58 Reviewed-on: https://go-review.googlesource.com/c/go/+/543515 Reviewed-by: Damien Neil <[email protected]> Auto-Submit: Damien Neil <[email protected]> Reviewed-by: qiulaidongfeng <[email protected]> LUCI-TryBot-Result: Go LUCI <[email protected]> Reviewed-by: Michael Knyszek <[email protected]>
1 parent cc7b4b3 commit 195c88b

File tree

2 files changed

+16
-11
lines changed

2 files changed

+16
-11
lines changed

src/net/http/server.go

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -575,9 +575,8 @@ type writerOnly struct {
575575
// to a *net.TCPConn with sendfile, or from a supported src type such
576576
// as a *net.TCPConn on Linux with splice.
577577
func (w *response) ReadFrom(src io.Reader) (n int64, err error) {
578-
bufp := copyBufPool.Get().(*[]byte)
579-
buf := *bufp
580-
defer copyBufPool.Put(bufp)
578+
buf := getCopyBuf()
579+
defer putCopyBuf(buf)
581580

582581
// Our underlying w.conn.rwc is usually a *TCPConn (with its
583582
// own ReadFrom method). If not, just fall back to the normal
@@ -807,11 +806,18 @@ var (
807806
bufioWriter4kPool sync.Pool
808807
)
809808

810-
var copyBufPool = sync.Pool{
811-
New: func() any {
812-
b := make([]byte, 32*1024)
813-
return &b
814-
},
809+
const copyBufPoolSize = 32 * 1024
810+
811+
var copyBufPool = sync.Pool{New: func() any { return new([copyBufPoolSize]byte) }}
812+
813+
func getCopyBuf() []byte {
814+
return copyBufPool.Get().(*[copyBufPoolSize]byte)[:]
815+
}
816+
func putCopyBuf(b []byte) {
817+
if len(b) != copyBufPoolSize {
818+
panic("trying to put back buffer of the wrong size in the copyBufPool")
819+
}
820+
copyBufPool.Put((*[copyBufPoolSize]byte)(b))
815821
}
816822

817823
func bufioWriterPool(size int) *sync.Pool {

src/net/http/transfer.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -410,9 +410,8 @@ func (t *transferWriter) writeBody(w io.Writer) (err error) {
410410
//
411411
// This function is only intended for use in writeBody.
412412
func (t *transferWriter) doBodyCopy(dst io.Writer, src io.Reader) (n int64, err error) {
413-
bufp := copyBufPool.Get().(*[]byte)
414-
buf := *bufp
415-
defer copyBufPool.Put(bufp)
413+
buf := getCopyBuf()
414+
defer putCopyBuf(buf)
416415

417416
n, err = io.CopyBuffer(dst, src, buf)
418417
if err != nil && err != io.EOF {

0 commit comments

Comments
 (0)