Measure slice, map and buffer preallocation
Measure slice, map and buffer preallocation
Preallocation reserves capacity before repeated growth. A slice made with make([]T, 0, n) starts empty and has room for n elements. A map capacity is a hint, not a limit. Buffer.Grow reserves space for additional bytes. Estimate from bounded, trusted input: an excessive capacity can increase memory retention or fail allocation.
Create the files shown below in a fresh directory, then run go test -count=1 -v ./... there. The separator lines are file labels, not source code. Go 1.23 is used for these local examples.
--- go.mod ---module example.test/lesson
go 1.23
--- lesson_test.go ---package lesson
import ( "slices" "testing")
var numbers []int
func fill(n int, pre bool) []int { var a []int if pre { a = make([]int, 0, n) } for i := 0; i < n; i++ { a = append(a, i) } return a}func TestLesson(t *testing.T) { if !slices.Equal(fill(64, false), fill(64, true)) { t.Fatal("different values") }}func BenchmarkGrow(b *testing.B) { for i := 0; i < b.N; i++ { numbers = fill(256, false) }}func BenchmarkReserve(b *testing.B) { for i := 0; i < b.N; i++ { numbers = fill(256, true) }}Both implementations produce the same elements. Compare allocs/op and B/op with the benchmark command from lesson 1, not just ns/op. Starting with length n instead of capacity n and then appending would produce n unwanted zero elements. Slice growth ratios are implementation details.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestLessonUse capacity hints for maps and buffers
--- go.mod ---module example.test/lesson
go 1.23
--- lesson_test.go ---package lesson
import ( "bytes" "maps" "testing")
var dict map[int]intvar text string
func table(pre bool) map[int]int { m := make(map[int]int) if pre { m = make(map[int]int, 128) } for i := 0; i < 128; i++ { m[i] = i * i } return m}func render(pre bool) string { var x bytes.Buffer if pre { x.Grow(256) } for i := 0; i < 128; i++ { x.WriteString("ab") } return x.String()}func TestLesson(t *testing.T) { if !maps.Equal(table(false), table(true)) || render(false) != render(true) || len(render(true)) != 256 { t.Fatal("output") }}func BenchmarkMapGrow(b *testing.B) { for i := 0; i < b.N; i++ { dict = table(false) }}func BenchmarkMapHint(b *testing.B) { for i := 0; i < b.N; i++ { dict = table(true) }}func BenchmarkBufferGrow(b *testing.B) { for i := 0; i < b.N; i++ { text = render(false) }}func BenchmarkBufferReserve(b *testing.B) { for i := 0; i < b.N; i++ { text = render(true) }}Compare the map variants with each other and the buffer variants with each other; they perform different operations. Map iteration order is not guaranteed, so compare key/value equality. Buffer.Grow guarantees room for the requested additional bytes, not a precise capacity or allocation count. Reuse a buffer only when its previous contents are no longer needed.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestLessonTry it locally
Build a string of 128 copies of "go" with strings.Builder, compare output with and without Grow and benchmark both. Use a fresh module with the same go.mod shown above; run go test -count=1 -v ./...
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Performance engineering 04: Measure slice, map and buffer preallocation
Check the lesson objective before moving on.
What does make([]int,0,100) create?
What is a map size hint?