go / intermediate
Snippet
Preventing Memory Leaks with Sub-Slice Copying
When you slice a slice, the new slice shares the same underlying array as the original. If a small sub-slice of a huge slice remains in memory, the garbage collector cannot reclaim the large underlying array. Copying the needed data into a new, smaller slice permits the large slice to be garbage collected.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package mainimport "fmt"func getImportantData(largeData []byte) []byte {result := make([]byte, 2)copy(result, largeData[:2])return result}func main() {bigSlice := make([]byte, 1000000)bigSlice[0], bigSlice[1] = 42, 99smallSlice := getImportantData(bigSlice)fmt.Printf("Length: %d, Capacity: %d\n", len(smallSlice), cap(smallSlice))}
Breakdown
1
result := make([]byte, 2)
Creates a new slice with length and capacity of 2, allocating a separate small underlying array.
2
copy(result, largeData[:2])
Copies only the required bytes from the large slice into the newly allocated slice.
3
return result
Returns the new small slice, allowing the caller to drop reference to the large slice.