Pidoku
Memory

Memory

IntermediateTopic5 lessons~4h 45m

Lessons, in order

About this topic

Go manages memory for you. This topic explains exactly how, because the difference between a service that spends 2% of its CPU on memory management and one that spends 30% is almost always a handful of decisions you can see once you know where to look.

#LessonThe question it answers
01Stack and HeapWhere do values live, and what does each place cost?
02Escape AnalysisHow does the compiler decide, and how do I read its decision?
03The AllocatorWhat happens, step by step, when the heap is asked for memory?
04The Garbage CollectorHow is unused memory found and freed while the program keeps running?
05Writing Allocation-Aware CodeHow do I cut allocations where it matters?

When you finish you can predict whether a line of code allocates, explain what GOGC and GOMEMLIMIT do, read a GC trace, and remove the allocations from a hot path.

flowchart LR
  V["A value is created"] --> EA{"Escape analysis:<br/>can it outlive the function?"}
  EA -->|"no"| ST["Goroutine stack<br/>free: just move a pointer"]
  EA -->|"yes"| AL["Allocator<br/>size class, span, per-thread cache"]
  AL --> HP[("Heap")]
  HP --> GC["Garbage collector<br/>mark what is reachable, sweep the rest"]
  GC -->|"freed spans"| AL
  class V neutral
  class EA queue
  class ST compute
  class AL,HP,GC memory

↑↓ navigate↵ openesc close

drag to pan · scroll to zoom