Learning more about the Go GC
The Go standard library offers functions that allow you to study the operation of the GC and learn more about what the GC covertly does. These functions are illustrated in the gColl.go
utility. The source code of gColl.go
is presented here in chunks.
package main
import (
"fmt"
"runtime"
"time"
)
We need the runtime
package because it allows us to get information about the Go runtime system, which among other things includes information about the operation of the GC.
func printStats(mem runtime.MemStats) {
runtime.ReadMemStats(&mem)
fmt.Println("mem.Alloc:", mem.Alloc)
fmt.Println("mem.TotalAlloc:", mem.TotalAlloc)
fmt.Println("mem.HeapAlloc:", mem.HeapAlloc)
fmt.Println("mem.NumGC:", mem.NumGC, "\n")
}
The main purpose of printStats()
is to avoid writing the same Go code multiple times. The runtime.ReadMemStats()
call...