What will change if you pass the initial capacity when creating a slice?
sobes.tech AI
Answer from AI
When creating a slice in Go with a specified initial capacity, you allocate memory for a certain number of elements in advance, although the length of the slice remains zero (unless the length is explicitly specified).
This affects the performance and behavior of the slice:
-
Avoids frequent allocations: When adding elements to the slice, if the capacity is insufficient, a new array with an increased size is allocated and data is copied. By setting the capacity in advance, you reduce the number of such operations.
-
Memory optimization: You control how much memory is allocated immediately, which is useful if the approximate number of elements is known beforehand.
Example:
s := make([]int, 0, 100) // length 0, capacity 100
for i := 0; i < 50; i++ {
s = append(s, i)
}
// No memory reallocation will occur here, as the capacity is sufficient
Without specifying the capacity, the slice will grow dynamically, which can lead to additional copying costs.