Skip to content

Instantly share code, notes, and snippets.

@leonid-shevtsov
Last active March 20, 2024 07:52
Show Gist options
  • Save leonid-shevtsov/42888fe1605d0038002967e0924d0abd to your computer and use it in GitHub Desktop.
Save leonid-shevtsov/42888fe1605d0038002967e0924d0abd to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"runtime"
)
func main() {
var stats runtime.MemStats
runtime.ReadMemStats(&stats)
fmt.Printf("initial:\nalloc=%d inuse=%d released=%d\n\n", stats.HeapAlloc, stats.HeapInuse, stats.HeapReleased)
var bigVar [][]int
for i := 0; i < 10; i++ {
bigVar = append(bigVar, make([]int, 100000))
}
runtime.ReadMemStats(&stats)
fmt.Printf("after big var:\nalloc=%d inuse=%d released=%d\n\n", stats.HeapAlloc, stats.HeapInuse, stats.HeapReleased)
runtime.GC()
bigVar[0] = make([]int, 100000)
runtime.ReadMemStats(&stats)
fmt.Printf("big var still in use:\nalloc=%d inuse=%d released=%d\n\n", stats.HeapAlloc, stats.HeapInuse, stats.HeapReleased)
runtime.GC()
runtime.ReadMemStats(&stats)
fmt.Printf("big var no longer in use:\nalloc=%d inuse=%d released=%d\n\n", stats.HeapAlloc, stats.HeapInuse, stats.HeapReleased)
}
@leonid-shevtsov
Copy link
Author

leonid-shevtsov commented Mar 20, 2024

In this example, GC is triggered explicitly for determinism. But it can trigger automatically at the time of any function call.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment