Hasty Briefsbeta

Bilingual

Understanding the Go Runtime: The Memory Allocator

2 days ago
  • #memory-management
  • #go-runtime
  • #performance
  • Go runtime's memory allocator manages heap memory efficiently by avoiding frequent OS system calls.
  • Memory allocation happens on the heap when data needs to outlive the function that created it, determined by escape analysis.
  • The allocator uses a three-level hierarchy (mcache, mcentral, mheap) to minimize lock contention during concurrent allocations.
  • Arenas (64MB chunks) are requested from the OS upfront, divided into 8KB pages, and further into spans for fixed-size objects.
  • Spans are organized into 68 size classes (8B to 32KB), with each span holding objects of a single size to reduce fragmentation.
  • Tiny objects (<16B) are packed together, while large objects (>32KB) bypass the hierarchy and go straight to the mheap.
  • The garbage collector works with the allocator using bitmaps (allocBits and gcmarkBits) to track live and freed objects.
  • A scavenger returns unused memory to the OS periodically, balancing performance and resource efficiency.