Go: Memory Management and Allocation
ℹ️ This article is based on Go 1.13.
Go memory management is automatically done by the standard library from the allocation of the memory to its collection when it is not used anymore. Although the developer does not have to deal with it, the underlying management done by Go is well optimized and full of interesting concepts.
Allocation on the heap
The memory management is designed to be fast in a concurrent environment and integrated with the garbage collector. Let’s start with a simple example:
package main
type smallStruct struct {
a, b int64
c, d float64
}
func main() {
smallAllocation()
}
//go:noinline
func smallAllocation() *smallStruct {
return &smallStruct{}
}
The annotation //go:noinline
will disable in-lining that would optimize the code by removing the function and, therefore, end up with no allocation.
Running the escape analysis command with go tool compile "-m" main.go
will confirm the allocation made by Go:
main.go:14:9: &smallStruct literal escapes to heap
Dumping the assembly code for this program, thanks to go tool compile -S main.go
, would also explicitly show us the allocation:
0x001d 00029 (main.go:14) LEAQ…