Maps, slices, and the Go GC
In this section, we discuss the operation of the Go GC in relation to maps and slices. The purpose of this section is to let you write code that makes the work of the GC easier.
Using slices
The example in this section uses a slice to store a large number of structures in order to show how slice allocation is related to the operation of the GC. Each structure stores two integer values. This is implemented in sliceGC.go
as follows:
package main
import (
"runtime"
)
type data struct {
i, j int
}
func main() {
var N = 80000000
var structure []data
for i := 0; i < N; i++ {
value := int(i)
structure = append(structure, data{value, value})
}
runtime.GC()
_ = structure[0]
}
The last statement, (_ = structure[0]
), is used to prevent the GC from garbage collecting the structure variable too early, as it is not referenced or used outside of the for
loop. The same technique will be used...