Understanding Go’s Memory Model

Before diving into optimization techniques, it’s essential to understand how Go manages memory at a fundamental level. Go’s memory model defines not just how memory is allocated and freed, but also the guarantees around memory access in concurrent programs.

Stack vs. Heap Allocation

Go uses a hybrid approach to memory allocation, utilizing both stack and heap:

package main

import (
	"fmt"
	"runtime"
)

func main() {
	// Stack allocation - x doesn't escape to the heap
	x := 42
	
	// Heap allocation - y escapes to the heap
	y := &x
	
	// Force GC to demonstrate the concept
	runtime.GC()
	
	// Print memory statistics
	var m runtime.MemStats
	runtime.ReadMemStats(&m)
	
	fmt.Printf("Stack variable: %d\n", x)
	fmt.Printf("Heap reference: %d\n", *y)
	fmt.Printf("Heap allocations: %d bytes\n", m.HeapAlloc)
}

The Go compiler uses escape analysis to determine whether a variable should be allocated on the stack or heap. Variables allocated on the stack are automatically freed when the function returns, while heap allocations are managed by the garbage collector.

Memory Layout and Alignment

Understanding memory layout and alignment is crucial for optimizing memory usage:

package main

import (
	"fmt"
	"unsafe"
)

// Inefficient memory layout
type Inefficient struct {
	a bool    // 1 byte + 7 bytes padding
	b int64   // 8 bytes
	c bool    // 1 byte + 7 bytes padding
	d int64   // 8 bytes
}

// Efficient memory layout
type Efficient struct {
	b int64   // 8 bytes
	d int64   // 8 bytes
	a bool    // 1 byte
	c bool    // 1 byte + 6 bytes padding
}

func main() {
	inefficient := Inefficient{}
	efficient := Efficient{}
	
	fmt.Printf("Inefficient struct size: %d bytes\n", unsafe.Sizeof(inefficient))
	fmt.Printf("Efficient struct size: %d bytes\n", unsafe.Sizeof(efficient))
}

This example demonstrates how field ordering in structs can significantly impact memory usage due to padding and alignment requirements. The inefficient struct consumes 32 bytes, while the efficient one uses only 24 bytes.