Slice length and capacity in Go - Time & Space Complexity
When working with slices in Go, it's important to understand how their length and capacity affect performance.
We want to see how operations grow as the slice size changes.
Analyze the time complexity of the following code snippet.
package main
func appendItems(slice []int, n int) []int {
for i := 0; i < n; i++ {
slice = append(slice, i)
}
return slice
}
This code appends n items to a slice, growing its length and possibly its capacity.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop runs n times, each time appending one item to the slice.
- How many times: Exactly n times, once per loop iteration.
Appending items grows with the number of items n, but capacity changes can cause extra work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 appends, some may cause capacity increase |
| 100 | About 100 appends, with a few capacity increases |
| 1000 | About 1000 appends, with several capacity increases |
Pattern observation: Most appends are simple, but occasionally the slice grows its capacity, causing extra copying work.
Time Complexity: O(n)
This means the total work grows roughly in direct proportion to the number of items appended.
[X] Wrong: "Each append always takes the same small amount of time."
[OK] Correct: Sometimes the slice needs to grow its capacity, which involves copying all elements and takes more time.
Understanding how slice operations scale helps you explain performance in real programs and shows you know how Go manages memory behind the scenes.
What if we pre-allocate the slice with enough capacity before appending? How would the time complexity change?
Practice
len() function return when used on a slice?Solution
Step 1: Understand the purpose of
Thelen()on sliceslen()function returns how many elements are currently stored in the slice.Step 2: Differentiate from capacity
Capacity is about how many elements the slice can hold before resizing, not the current count.Final Answer:
The number of elements currently in the slice -> Option DQuick Check:
len(slice) = current element count [OK]
- Confusing length with capacity
- Thinking len returns memory size
- Assuming len gives last index
Solution
Step 1: Recall the
makefunction signature for slicesmake([]T, length, capacity)creates a slice with given length and capacity.Step 2: Match length and capacity values
To get length 3 and capacity 5, usemake([]int, 3, 5).Final Answer:
make([]int, 3, 5) -> Option BQuick Check:
make([]int, length, capacity) [OK]
- Swapping length and capacity arguments
- Using slice literal instead of make
- Omitting capacity when needed
nums := make([]int, 2, 4) nums[0] = 10 nums[1] = 20 fmt.Println(len(nums), cap(nums))
Solution
Step 1: Analyze slice creation
make([]int, 2, 4)creates a slice with length 2 and capacity 4.Step 2: Check length and capacity after assignments
Assigning values to existing indices does not change length or capacity.Final Answer:
2 4 -> Option CQuick Check:
len = 2, cap = 4 [OK]
- Confusing length with capacity
- Assuming capacity equals length after assignment
- Thinking length changes when assigning values
arr := []int{1, 2, 3, 4, 5}
slice := arr[1:3]
fmt.Println(len(slice), cap(slice))What is the correct output?
Solution
Step 1: Determine length of the slice
The slice is from index 1 to 3 (exclusive), so length = 3 - 1 = 2.Step 2: Calculate capacity of the slice
Capacity is from start index to end of original array: 5 - 1 = 4.Final Answer:
2 4 -> Option AQuick Check:
len = 2, cap = 4 from slice indices [OK]
- Using slice length as capacity
- Confusing slice end index with capacity
- Assuming capacity equals original array length
s := make([]int, 3, 5). You append two elements to it. What will be the length and capacity of s after these appends?Solution
Step 1: Understand initial slice size
Slicesstarts with length 3 and capacity 5.Step 2: Append two elements within capacity
Appending two elements increases length to 5, capacity remains 5 because it is not exceeded.Final Answer:
Length 5, Capacity 5 -> Option AQuick Check:
Appending within capacity keeps capacity same [OK]
- Assuming capacity doubles immediately after append
- Confusing length with capacity after append
- Thinking capacity increases by 1 per append
Ready to prove it?
Pass the test and this pattern moves unknown
