-
Notifications
You must be signed in to change notification settings - Fork 18k
runtime: append to nil slice slower than make and copy #14718
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
/cc @randall77 |
On my machine, both benchmarks improve from 1.6 -> tip (SSA) but the gap between them remains.
|
The major reason is that when you do make([]byte, n), you get an allocation with len==cap==n. The runtime doesn't have to do much work to decide what to allocate and what to zero. When you do append(nil, ..slice of n bytes..), you actually get more capacity. In this case, you get a slice with a length of 22 and a capacity of 32. The increased capacity is there to anticipate future appends. The runtime spends some additional time computing what the right capacity should be and initializing those extra bytes. Also, the append path generally has more overhead, see #11419 for an example. We should be able to fix some of this, but probably not all. For instance, there is a divide to compute how many extra elements we can fit when we round the allocation up to a size class (runtime/slice.go:92). That divide would be hard to get rid of, and probably accounts for a good chunk of the difference you're seeing. |
Closing this bug, then. Sounds like it's working as expected. |
Please answer these questions before submitting your issue. Thanks!
go version
)?go version go1.6 darwin/amd64
go env
)?GOARCH="amd64" GOOS="darwin"
(Use play.golang.org to provide a runnable example, if possible.)
The two patterns would produce the same code and have the same performance.
Instead, the make and copy pattern (
BenchmarkBBytes
) seems to be faster by about 12 ns, or 16%. See cockroachdb/cockroach#4963.The text was updated successfully, but these errors were encountered: