Middle
Kui palju suureneb slice suurus, kasutades funktsiooni append?
sobes.tech AI
Vastus AI-lt
The size of a slice can increase in various ways depending on the current capacity cap(slice):
- If the capacity is insufficient: The new capacity will be at least double the current capacity if it is less than 1024. If it is greater than 1024, the capacity will increase by approximately 25% of the current capacity until it becomes sufficient. Then it can be adjusted upward.
- If the capacity is sufficient: The size of the slice increases exactly by the number of added elements, and the capacity remains unchanged.
// Example of append behavior when there is not enough capacity
s := make([]int, 0, 0) // size 0, capacity 0
s = append(s, 1) // size 1, capacity 1. (0 -> 1)
s = append(s, 2) // size 2, capacity 2. (1 -> 2)
s = append(s, 3) // size 3, capacity 4. (2 -> 4)
s = append(s, 4) // size 4, capacity 4
s = append(s, 5) // size 5, capacity 8. (4 -> 8)
s2 := make([]int, 0, 1025) // size 0, capacity 1025
s2 = append(s2, make([]int, 500)...) // size 500, capacity 1025 (sufficient)
s2 = append(s2, make([]int, 1000)...) // size 1500, approximately 1025 + 1025*0.25 + epsilon
The specific algorithm for capacity growth is located inside the runtime and may vary between Go versions. However, the general rules (doubling up to 1024, increasing by about 25% after) remain in effect.