Golang Garbage Collector 101
Take a look at GC running visually
Quick Look at Garbage Collector
A simple program that creates a byte array of 100000000 elements and lets print the memory allocations.
Understanding the code
There is a package in Golang standard library called runtime
which contains alot of useful function like :
runtime.ReadMemStats(&mem)
runtime.GC()
Take a loot at : https://golang.org/pkg/runtime/
func ReadMemStats
ReadMemStats populates m with memory allocator statistics.
The returned memory allocator statistics are up to date as of the call to ReadMemStats. This is in contrast with a heap profile, which is a snapshot as of the most recently completed garbage collection cycle.
GC runs a garbage collection and blocks the caller until the garbage collection is complete. It may also block the entire program.
Run this program using the following flag :
Output i receive [ don't get scared, will clean up ] :
Let look at the second run :
In first line : ignoring the value from CPU profiler, take a look at "95->95>0 MB". The first number is the heap size when the garbage collector is about to run. The second value is the heap size when the garbage collector ends its operation. The last value is the size of the live heap that is 0
It allocated 100081456 bytes of memory, more than the 100000000 becuase that is the length of slices we specified, and 100081456 bytes is the capacity of the slices or simply everytime you make a slices, some extra memory is allocated with it in case the size needs to expand in future.
Thus before running through the second iteration of the loop, it clears out the memory allocated during the first
Last updated