Escape Analysis
ELI5 - The Vibe Check
Escape analysis is a compiler playing detective, trying to prove that an object you allocated never actually escapes the function it was created in, meaning nothing outside can ever see or keep a reference to it. If the compiler can prove that, it can skip the heap entirely and just put the object on the stack, which gets cleaned up for free when the function returns instead of waiting around for the garbage collector.
Real Talk
Escape analysis is a compiler optimization that determines whether an object's lifetime and visibility are provably confined to the function or thread that created it. If an object does not escape, the compiler can allocate it on the stack instead of the heap, or eliminate the allocation entirely through scalar replacement, avoiding both allocation overhead and future garbage collection pressure. Go and the JVM both perform escape analysis automatically.
Show Me The Code
func sum(nums []int) int {
total := 0 // escape analysis: stays on the stack, never returned or referenced
for _, n := range nums { total += n }
return total
}
When You'll Hear This
"Escape analysis kept that struct on the stack, that's why the allocation profile shows nothing there." / "Returning a pointer to a local variable forces it to escape to the heap."
Related Terms
Garbage Collection (GC)
Garbage collection is your programming language's automatic cleanup crew. When you create variables and objects, they take up memory.
JIT Warmup
A JIT compiler starts out running your code the slow, simple way, an interpreter, while it quietly watches which parts get called the most.
Memory Fragmentation
Memory fragmentation is what happens when your program has plenty of free memory in total, but it's scattered around in small, useless chunks instead of on...
Profiling
Profiling is watching your program run and keeping score of where the time and memory actually go, instead of guessing.