Junior — Middle
Why is it important to consider the capacity of slices when working with arrays in Go?
sobes.tech AI
Answer from AI
In Go, slices are dynamic structures that contain a pointer to an array, a length, and a capacity. The capacity of a slice determines how many elements it can hold without allocating new memory.
It is important to consider capacity because:
- When adding elements using
append, if the length of the slice exceeds the capacity, a new array with increased capacity is allocated and data is copied, which affects performance. - Knowing the capacity allows for efficient memory management and avoiding unnecessary allocations.
Example:
s := make([]int, 0, 5) // length 0, capacity 5
fmt.Println(len(s), cap(s)) // 0 5
s = append(s, 1, 2, 3, 4, 5)
fmt.Println(len(s), cap(s)) // 5 5
s = append(s, 6) // capacity exceeded, a new array is allocated
fmt.Println(len(s), cap(s)) // 6 10 (approximately)
Thus, controlling the capacity can optimize slice operations.