0 day streak
go / intermediate
Snippet

Isolating Sub-slices to Prevent Memory Retention Leaks

In Go, a slice is a header pointing to an underlying array. When you create a sub-slice from a large slice (e.g., largeSlice[:2]), the garbage collector cannot reclaim the underlying array because the new slice still references it. To prevent memory leaks, you should copy the required elements into a new slice, allowing the large array to be collected.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package main
import "fmt"
func getFirstTwoElements(largeSlice []int) []int {
result := make([]int, 2)
copy(result, largeSlice[:2])
return result
}
func main() {
largeData := make([]int, 1000000)
for i := 0; i < 1000000; i++ {
largeData[i] = i
}
smallActiveSlice := getFirstTwoElements(largeData)
fmt.Printf("Length: %d, Capacity: %d\n", len(smallActiveSlice), cap(smallActiveSlice))
}
Breakdown
1
result := make([]int, 2)
Allocates a new slice of length and capacity 2, independent of the original large array.
2
copy(result, largeSlice[:2])
Copies the first two elements from largeSlice into the newly allocated result slice.
3
largeData := make([]int, 1000000)
Simulates a large allocation of memory containing 1 million integers.
4
smallActiveSlice := getFirstTwoElements(largeData)
Obtains the copied slice, allowing the largeData array to be garbage collected immediately after.