diff --git a/lib/go/thrift/binary_protocol.go b/lib/go/thrift/binary_protocol.go index 3f2843ef96..78d9f04206 100644 --- a/lib/go/thrift/binary_protocol.go +++ b/lib/go/thrift/binary_protocol.go @@ -597,14 +597,18 @@ func safeReadBytes(size int32, trans io.Reader) ([]byte, error) { if size < 0 { return nil, nil } - if size > bytes.MinRead { - // Use bytes.Buffer to prevent allocating size bytes when size is very large - buf := new(bytes.Buffer) - _, err := io.CopyN(buf, trans, int64(size)) - return buf.Bytes(), err - } - // Allocate size bytes - b := make([]byte, size) - n, err := io.ReadFull(trans, b) - return b[:n], err + + // Fast path for reads smaller than 10 MiB that only allocates exactly + // what is asked for. + const readLimit = 10 * 1024 * 1024 + if size < readLimit { + b := make([]byte, size) + n, err := io.ReadFull(trans, b) + return b[:n], err + } + + // Use bytes.Buffer to prevent allocating size bytes when size is very large + buf := new(bytes.Buffer) + _, err := io.CopyN(buf, trans, int64(size)) + return buf.Bytes(), err }