Senior
What happens when the capacity of a slice is exhausted and another element is added?
sobes.tech AI
Answer from AI
When the capacity of a slice is exhausted and a new element is added via append, the following happens:
-
A new array with increased capacity is created. Usually, the capacity increases by about 2 times, but the exact algorithm depends on the implementation and the size of the slice.
-
The contents of the old array are copied into the new one.
-
The new element is added to the new array.
-
The slice starts referencing the new array with the updated length and capacity.
This means that the append operation when capacity is exhausted leads to memory allocation and data copying, which can be costly. Therefore, if the size is known in advance, it is better to create a slice with the required capacity using make.
Example:
s := make([]int, 0, 2) // capacity 2
s = append(s, 1, 2) // now length is 2, capacity 2
s = append(s, 3) // capacity exhausted, a new array with capacity 4 is created