]> Cypherpunks repositories - gostls13.git/commitdiff
net/http: use pointers to array for copyBufPool
authorJorropo <jorropo.pgm@gmail.com>
Wed, 8 Nov 2023 15:08:26 +0000 (16:08 +0100)
committerGopher Robot <gobot@golang.org>
Tue, 21 Nov 2023 00:52:06 +0000 (00:52 +0000)
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 <dneil@google.com>
Auto-Submit: Damien Neil <dneil@google.com>
Reviewed-by: qiulaidongfeng <2645477756@qq.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
src/net/http/server.go
src/net/http/transfer.go

index 7fa785dfeeb3c3a13b532754e7ed57ba654a4536..36a03f4a32db37f6b19746c9b37df72f822df878 100644 (file)
@@ -575,9 +575,8 @@ type writerOnly struct {
 // to a *net.TCPConn with sendfile, or from a supported src type such
 // as a *net.TCPConn on Linux with splice.
 func (w *response) ReadFrom(src io.Reader) (n int64, err error) {
-       bufp := copyBufPool.Get().(*[]byte)
-       buf := *bufp
-       defer copyBufPool.Put(bufp)
+       buf := getCopyBuf()
+       defer putCopyBuf(buf)
 
        // Our underlying w.conn.rwc is usually a *TCPConn (with its
        // own ReadFrom method). If not, just fall back to the normal
@@ -807,11 +806,18 @@ var (
        bufioWriter4kPool sync.Pool
 )
 
-var copyBufPool = sync.Pool{
-       New: func() any {
-               b := make([]byte, 32*1024)
-               return &b
-       },
+const copyBufPoolSize = 32 * 1024
+
+var copyBufPool = sync.Pool{New: func() any { return new([copyBufPoolSize]byte) }}
+
+func getCopyBuf() []byte {
+       return copyBufPool.Get().(*[copyBufPoolSize]byte)[:]
+}
+func putCopyBuf(b []byte) {
+       if len(b) != copyBufPoolSize {
+               panic("trying to put back buffer of the wrong size in the copyBufPool")
+       }
+       copyBufPool.Put((*[copyBufPoolSize]byte)(b))
 }
 
 func bufioWriterPool(size int) *sync.Pool {
index dffff56b31e94ff8345eedb769948032bf34d9e0..d787258487d1673a3ee41ac6bb83312805d2cf55 100644 (file)
@@ -410,9 +410,8 @@ func (t *transferWriter) writeBody(w io.Writer) (err error) {
 //
 // This function is only intended for use in writeBody.
 func (t *transferWriter) doBodyCopy(dst io.Writer, src io.Reader) (n int64, err error) {
-       bufp := copyBufPool.Get().(*[]byte)
-       buf := *bufp
-       defer copyBufPool.Put(bufp)
+       buf := getCopyBuf()
+       defer putCopyBuf(buf)
 
        n, err = io.CopyBuffer(dst, src, buf)
        if err != nil && err != io.EOF {