Memory Allocation and GC

Understanding Go's memory management is the key to writing truly high-performance applications. Go handles memory automatically through a Garbage Collector (GC), but a developer's choices in data structure and function design significantly impact how hard the GC has to work.


1. Stack vs. Heap Allocation


2. Escape Analysis

The Go compiler performs Escape Analysis to decide whether a variable should stay on the stack or move to the heap.

func getID() *int {
    id := 42
    return &id // 'id' escapes to the heap because its pointer is returned
}

3. The Garbage Collector: Mark and Sweep

Go uses a Concurrent Mark and Sweep garbage collector. It is designed for Low Latency (minimal "Stop-the-World" time), making it ideal for web servers where consistent response times are vital.

  1. Marking: The GC traverses the heap and marks all objects that are still "Reachable" by the program.
  2. Sweeping: It reclaims the memory of all objects that were NOT marked.

4. Tuning the GC with GOGC

You can control how aggressively the GC runs using the GOGC environment variable.


5. Memory Safety

Go is a memory-safe language. It prevents:


Interview Pro-Tips: What is a "Stop The World" (STW) event?

If an interviewer asks about performance jitters:


Technical Summary

  1. Stack: Fast, automatic, no GC overhead.
  2. Heap: Flexible but expensive.
  3. Escape: Variables "escape" if they are shared outside their local scope.
  4. Pointers: Using pointers usually triggers heap allocation. flagship flagship