When go runtime allocates memory from heap, and when from stack?

In Go, memory allocation is managed by the Go runtime, and it decides whether to allocate memory from the heap or the stack based on the lifetime and size of the variables.

Allocation from the Stack:

  • The stack is used for storing local variables and function call frames.
  • Memory is allocated on the stack for each Goroutine when it enters a function.
  • Local variables (including function arguments) are usually allocated on the stack.
  • The stack memory is automatically reclaimed when the function returns.
  • Since stack allocation and deallocation are fast and deterministic, it makes Goroutine creation and destruction very efficient.
  • However, the size of the stack is limited, and allocating large objects on the stack can lead to stack overflow.

Allocation from the Heap:

  • The heap is used for dynamically allocated memory that needs to persist across multiple function calls.
  • Objects whose lifetime extends beyond the function’s scope are typically allocated on the heap.
  • Slices and maps, which are dynamic in size, are allocated on the heap.
  • Memory allocated on the heap needs to be explicitly deallocated to avoid memory leaks.
  • The Go runtime includes a garbage collector (GC) to automatically reclaim unused memory from the heap.
  • Heap allocation is slower compared to stack allocation due to the overhead of GC and memory management.

In summary, the Go runtime automatically determines whether to allocate memory on the stack or the heap based on the variables’ lifetime and size. Stack allocation is used for local variables and function call frames, while the heap is used for dynamically allocated memory and objects with a longer lifetime. The GC takes care of reclaiming memory from the heap that is no longer in use, making Go a garbage-collected language that reduces the burden of manual memory management.

error: Content is protected !!