Sobes.tech
Middle+

How is the heap organized in Go language?

sobes.tech AI

Answer from AI

In Golang, the heap is a memory area where dynamically allocated objects are placed. Memory management is handled automatically by the garbage collector.

Key aspects:

  • Dynamic allocation: Small objects with short lifetimes, where the compiler cannot prove that their lifetime is limited to the function or stack scope, or objects allocated with new or by taking an address (&), are usually placed on the heap.
  • Garbage collector (GC): Go uses a concurrent, tri-color, Mark-and-Sweep garbage collector. It operates alongside the program execution, minimizing pauses.
    • Mark: The GC traverses reachable objects from root pointers (local variables on stacks, global variables) and marks them as "alive".
    • Sweep: The GC scans the entire accessible heap and frees memory occupied by objects that were not marked as "alive".
    • Concurrent: The GC runs in separate goroutines, reducing delays in the main program.
  • Escape Analysis: The Golang compiler performs escape analysis to determine whether a variable or value points to the stack or the heap. If a variable or struct field might be accessible after returning from the current goroutine, it is likely allocated on the heap. Otherwise, it can be allocated on the stack.
    // Example of escape analysis.
    // This object is likely to be allocated on the heap,
    // as a pointer is returned.
    func createPoint() *Point {
        p := Point{X: 1, Y: 2}
        return &p // Pointer "escapes" from the function
    }
    
    // This object is likely to be allocated on the stack,
    // as it is not accessible after the function ends.
    func processValue() {
        val := 10
        println(val)
    }
    
    type Point struct {
        X, Y int
    }
    
  • Division into Arenas: The heap in Go can be divided into multiple arenas, which helps the garbage collector work more efficiently, especially on multi-processor systems.
  • Using mmap: Golang uses the system call mmap (Memory Map) to allocate large blocks of virtual memory for the heap.
  • Contiguity: Unlike some languages, Go does not guarantee physical contiguity of objects in the heap. Memory can be fragmented.
  • No manual memory management: Developers do not need to explicitly allocate or free memory in the heap. GC handles this automatically.

The stack and heap in Golang serve different roles:

Memory Area Purpose Management Lifetime
Stack Local variables, function parameters, return addresses Automatic (on function entry/exit) Limited to function execution time
Heap Dynamically allocated objects, those "escaping" the stack, large structures Garbage collector (GC) Determined by reachability from roots