Inspect scavenging and allocation profiles
Inspect scavenging and allocation profiles
Scavenging returns unused physical heap memory to the OS, while GC identifies unreachable objects and sweeping makes their storage reusable. The scavenger does not free reachable objects. HeapReleased measures memory returned to the OS; RSS depends on the OS and other mappings. debug.FreeOSMemory forces a GC followed by an attempt to return as much memory as possible; it is a diagnostic tool, not a routine per-request optimization. A heap profile describes sampled live allocations as of the most recently completed GC; an allocs profile uses the same underlying data with total allocated space as its default view, including objects already freed.
package main
import ( "bytes" "fmt" "runtime" "runtime/pprof")
var held []byte
func main() { held = make([]byte, 1<<20) held[0] = 7 runtime.GC() var b bytes.Buffer if e := pprof.Lookup("heap").WriteTo(&b, 0); e != nil { panic(e) } fmt.Println(b.Len() > 0, held[0]) held = nil}WriteTo with debug=0 emits a compressed pprof profile. A nonempty buffer proves data was written, not that every allocation was sampled. To inspect, write the buffer to a private file heap.pprof (use os.WriteFile with permissions 0600 for a new file in a private directory) and run go tool pprof -top -sample_index=inuse_space heap.pprof. Compare -sample_index=alloc_space to investigate cumulative churn. Profiles can reveal function names and paths.
Expected output:
true 7Observe idle and released heap safely
package main
import ( "fmt" "runtime" "runtime/debug")
var held []byte
func main() { held = make([]byte, 2<<20) held[0] = 1 held = nil debug.FreeOSMemory() var m runtime.MemStats runtime.ReadMemStats(&m) fmt.Println(m.HeapIdle >= m.HeapReleased)}This standalone experiment releases its reference and requests scavenging, then checks a documented relationship between idle and released bytes. It does not require either counter to increase by a fixed amount: GC timing, OS behavior and other runtime allocations affect the observation. Avoid calling FreeOSMemory in a hot path; measure memory and latency first.
Expected output:
trueTry it locally
Capture the allocs profile after allocating a 64 KiB buffer and storing it globally. Call GC, write the profile to a bytes.Buffer and verify nonempty output and buffer length.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Runtime allocation 06: Inspect scavenging and allocation profiles
Check the lesson objective before moving on.
What is the scavenger responsible for?
Which profile view helps investigate cumulative allocated bytes?