Skip to content

Instantly share code, notes, and snippets.

@leonid-shevtsov
Last active March 20, 2024 07:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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

initial:
alloc=102384 inuse=450560 released=3448832

after big var:
alloc=8137256 inuse=8486912 released=3661824

big var still in use:
alloc=8939816 inuse=9281536 released=2826240

big var no longer in use:
alloc=108456 inuse=442368 released=2793472

@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