Skip to content

Escape Analysis

Spicy — senior dev territorylanguages

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."

Made with passive-aggressive love by manoga.digital. Powered by Claude.