Grow Preallocates Slice Capacity

Reserve capacity for upcoming appends with slices.Grow so bulk inserts stop reallocating, and compare against the repeatedly-growing baseline.

GoData Integrity

Code

gosnippet
25 lines
package main

import (
	"fmt"
	"slices"
)

func main() {
	src := []int{1, 2, 3}

	// Grow 保证容量至少再容纳 n 个元素:随后的 append 不再触发重新分配
	grown := slices.Grow(src, 1000)
	fmt.Println("room after grow:", cap(grown)-len(grown) >= 1000)

	// 复用扩好的容量连续追加
	total := append(grown, 4, 5, 6)
	fmt.Println("len:", len(total))

	// 对照:从零开始的 append 会随增长多次扩容搬移
	slow := []int{}
	for i := 0; i < 1000; i++ {
		slow = append(slow, i)
	}
	fmt.Println("slow filled:", len(slow) == 1000, "cap sufficient:", cap(slow) >= 1000)
}

Inside the snippet

Count the function main as the entire surface area of Grow Preallocates Slice Capacity.

The one repetition in this snippet is the loop for i := 0; i < 1000; i++.

Putting it to use

The demo output is labeled (room after grow:, len:, slow filled:), so the output doubles as a step-by-step trace of what the file did.

Core lines

total := append(grown, 4, 5, 6)
slow = append(slow, i)

Interactive Tools for This Topic

FAQ

What does Grow Preallocates Slice Capacity print when run?
Run it as a complete program — the output lines carry labels such as `room after grow:`, `len:`, `slow filled:`.