1
0
mirror of https://github.com/golang/go synced 2024-11-26 17:46:57 -07:00

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 <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>
This commit is contained in:
Jorropo 2023-11-08 16:08:26 +01:00 committed by Gopher Robot
parent cc7b4b3c36
commit 195c88b202
2 changed files with 16 additions and 11 deletions

View File

@ -575,9 +575,8 @@ type writerOnly struct {
// to a *net.TCPConn with sendfile, or from a supported src type such // to a *net.TCPConn with sendfile, or from a supported src type such
// as a *net.TCPConn on Linux with splice. // as a *net.TCPConn on Linux with splice.
func (w *response) ReadFrom(src io.Reader) (n int64, err error) { func (w *response) ReadFrom(src io.Reader) (n int64, err error) {
bufp := copyBufPool.Get().(*[]byte) buf := getCopyBuf()
buf := *bufp defer putCopyBuf(buf)
defer copyBufPool.Put(bufp)
// Our underlying w.conn.rwc is usually a *TCPConn (with its // Our underlying w.conn.rwc is usually a *TCPConn (with its
// own ReadFrom method). If not, just fall back to the normal // own ReadFrom method). If not, just fall back to the normal
@ -807,11 +806,18 @@ var (
bufioWriter4kPool sync.Pool bufioWriter4kPool sync.Pool
) )
var copyBufPool = sync.Pool{ const copyBufPoolSize = 32 * 1024
New: func() any {
b := make([]byte, 32*1024) var copyBufPool = sync.Pool{New: func() any { return new([copyBufPoolSize]byte) }}
return &b
}, 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 { func bufioWriterPool(size int) *sync.Pool {

View File

@ -410,9 +410,8 @@ func (t *transferWriter) writeBody(w io.Writer) (err error) {
// //
// This function is only intended for use in writeBody. // This function is only intended for use in writeBody.
func (t *transferWriter) doBodyCopy(dst io.Writer, src io.Reader) (n int64, err error) { func (t *transferWriter) doBodyCopy(dst io.Writer, src io.Reader) (n int64, err error) {
bufp := copyBufPool.Get().(*[]byte) buf := getCopyBuf()
buf := *bufp defer putCopyBuf(buf)
defer copyBufPool.Put(bufp)
n, err = io.CopyBuffer(dst, src, buf) n, err = io.CopyBuffer(dst, src, buf)
if err != nil && err != io.EOF { if err != nil && err != io.EOF {