Garbage collection automatically tracks and frees heap allocations that are no longer needed. It does not reclaim data merely because a program has stopped using it in the way a developer intended: references can keep that data alive. section 12.9 section 3.10.2
Go uses concurrent mark-and-sweep: a collection cycle identifies objects still in use and reclaims unreferenced objects. Most work runs alongside the application, but each cycle also includes two stop-the-world pauses. A periodic scavenger can later return unneeded memory to the operating system. section 12.9.1
A short slice can retain a large allocation
A slice of two Foo values can keep the original 1,000-element backing array alive. Because each Foo contains a byte slice, the other 998 byte-slice allocations remain referenced by that array even though they are outside the returned slice’s length. runtime.KeepAlive makes the retained reference explicit during the measurement. section 3.10.2
func main() {
foos := make([]Foo, 1_000) #1
printAlloc()
for i := 0; i < len(foos); i++ { #2
foos[i] = Foo{
v: make([]byte, 1024*1024),
}
}
printAlloc()
two := keepFirstTwoElementsOnly(foos) #3
runtime.GC() #4
printAlloc()
runtime.KeepAlive(two) #5
}
func keepFirstTwoElementsOnly(foos []Foo) []Foo {
return foos[:2]
}
The example allocates 1 MB per element, keeps only a two-element slice, and runs a collection. section 3.10.2
To release the unwanted allocations, copy the first two elements into a new slice and drop other references to the original array. Alternatively, set the unwanted elements’ slice fields to nil before returning the subslice; this changes the shared backing array. section 3.10.2
func keepFirstTwoElementsOnly(foos []Foo) []Foo {
res := make([]Foo, 2)
copy(res, foos)
return res
}
Copying the retained elements gives them a separate backing array. section 3.10.2
Deleting map entries may not shrink the map
In the map implementation described here, deleting entries clears their slots but leaves the map’s buckets allocated. After adding and deleting one million entries, a collection reduced the measured heap from 461 MB to 293 MB while the map remained alive. Collection of entries did not mean collection of the map itself. section 3.12
Collection frequency also affects performance. With the described default GOGC value of 100, the next collection is triggered when the heap doubles from its size after the previous collection. A sudden heap increase can cause frequent cycles and pauses; increasing GOGC may reduce that pressure, but a larger heap takes longer to clean. Evaluate changes under production load rather than assuming linear benefits. section 12.9.1 section 12.9.2
$ GODEBUG=gctrace=1 go test -bench=. -v
Enable GC trace output while running benchmarks to inspect collection behavior. section 12.9.1








