While reading Dave Cheney’s post, I noticed a benchmark that highlights an eight-byte allocation improvement.
1 | func BenchmarkSortStrings(b *testing.B) { |
The benchmark sorts a []string and reports allocations.
These lines:
1 | var ss sort.StringSlice = s |
are equivalent to:
1 | sort.Strings(s) |
Both paths convert []string into something implementing sort.Interface.
If you know how iface works, the data word holds the value — one machine word (8 bytes on 64-bit). A slice is 24 bytes: backing-array pointer, length, and capacity. It does not fit in the data word, so the runtime stores a pointer to the slice. Creating that pointer can force the slice to escape to the heap, because the compiler cannot prove the original ss outlives si.
That is where the allocation shows up.
Benchmark on Go 1.16:
1 | $ go test sort_test.go -bench . -benchmem |
Twenty-four bytes per op — where is the “eight bytes saved”?
Compared to before Go 1.16, for example Go 1.15:
1 | $ go1.15 test sort_test.go -bench . -benchmem |
The runtime gained a 24-byte size class so three-word objects are not rounded up to 32 bytes. Commit: runtime: add 24 byte allocation size class.
Questions? Leave a comment below or email: newbvirgil@gmail.com![]()
