Open
Description
What version of Go are you using (go version
)?
$ go version go version go1.17.5 linux/amd64
Does this issue reproduce with the latest release?
Yes.
What operating system and processor architecture are you using (go env
)?
go env
Output
$ go env GO111MODULE="" GOARCH="amd64" GOBIN="" GOCACHE="/home/vagrant/.cache/go-build" GOENV="/home/vagrant/.config/go/env" GOEXE="" GOEXPERIMENT="" GOFLAGS="" GOHOSTARCH="amd64" GOHOSTOS="linux" GOINSECURE="" GOMODCACHE="/home/vagrant/pkg/mod" GONOPROXY="" GONOSUMDB="" GOOS="linux" GOPATH="/home/vagrant" GOPRIVATE="" GOPROXY="https://proxy.golang.org,direct" GOROOT="/usr/local/go" GOSUMDB="sum.golang.org" GOTMPDIR="" GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64" GOVCS="" GOVERSION="go1.17.5" GCCGO="gccgo" AR="ar" CC="gcc" CXX="g++" CGO_ENABLED="1" GOMOD="/home/vagrant/src/github.com/cortexproject/cortex/go.mod" CGO_CFLAGS="-g -O2" CGO_CPPFLAGS="" CGO_CXXFLAGS="-g -O2" CGO_FFLAGS="-g -O2" CGO_LDFLAGS="-g -O2" PKG_CONFIG="pkg-config" GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build2696308846=/tmp/go-build -gno-record-gcc-switches"
What did you do?
Called ioutil.ReadAll
to read everything from an http response.
What did you expect to see?
Reasonable memory and CPU usage.
What did you see instead?
~60% more memory is allocated when using ioutil.ReadAll
compared with bytes.Buffer.ReadFrom
.
See prometheus/client_golang#976.
#46564 is making the same complaint, although it was solved in a different way.
The underlying reason is that ReadAll()
uses append
to resize its buffer, which goes up by a factor of 1.25 (slightly more in latest Go, but asymptotically the same) each time.
One might measure these alternatives on various axes:
- number of bytes allocated and freed
- max size of heap required to read a given size
- amount of copying while resizing
- percentage waste in returned buffer
The current implementation is better on the last one, and much worse on all the others.