Memory Management

Memory Management

Go automatically manages memory with its Garbage Collector.

Most of variables allocation definition is done at compile time. But they can be moved in certain circunstances at runtime.

circle-info

You can run it manually, although not recommended with runtime.GC().

circle-check

Tips for better performance

circle-exclamation

Stack

Used for small, local, short-lived, and that do not escape the function variables.

Automatically cleaned up when function exits. (That's why short-lived)

circle-exclamation
circle-check

Heap

Used for large or long-lived variables (slower, garbage-collected)

They live until garbage collected. (That's why long-lived)

circle-info

There is no fixed size at which Go moves an array/map to the heap.

Condition
Example
Why goes to Heap

A closure captures a variable

func() { x++ }

The variable outlives the function

Returning a pointer to a local variable

return &x

The local variable must persist

Structs stored in an interface

var i interface{} = MyStruct{}

Interfaces store references

Large arrays/slices (Maps always)

make([]int, 100000)

Avoids stack overflow

Structs passed by reference

func test(p *Person){}

Explicit heap allocation

General rules for Arrays/Maps/Slices

circle-exclamation
circle-exclamation

Memory Leaks

circle-check

Usually happen when Heap memory isn't freed properly.

Scenario
Fix

Global variables holding large data

Avoid unnecessary global variables

Unclosed Goroutines

Use sync.WaitGroup or context.Context to stop them

Slices growing without limit

Use make() with a sensible capacity

Forgotten closures holding memory

Set function references to nil when no longer needed

Last updated