liveBook · Manning

Memory allocation

As explained in 100 Go Mistakes and How to Avoid Them

Memory allocation is the process of reserving memory for data or runtime objects.

In Go, a variable can be allocated on the stack or the heap. Each goroutine has its own stack; the heap is shared. Stack allocation is generally faster and self-cleaning, while heap allocation takes more work and adds pressure to the garbage collector. section 12.5 section 12.5.1

Returning a pointer to avoid a copy is not necessarily faster. If the compiler cannot prove that a variable will not be referenced after its function returns, it allocates the variable on the heap. In general, sharing down stays on the stack, while sharing up escapes to the heap; compiler decisions can change between Go versions. section 12.5.1 section 12.5.2

func main() {
    a := 3
    b := 2
 
    c := sumValue(a, b)        #1
    println(c)                 #2
}
 
//go:noinline                  #3
func sumValue(x, y int) int {
    z := x + y
    return z
}

This function returns the sum by value. In the comparison, inlining is disabled to make the allocation behavior visible. section 12.5.1

func main() {
    a := 3
    b := 2
 
    c := sumPtr(a, b)
    println(*c)
}
 
//go:noinline
func sumPtr(x, y int) *int {     #1
    z := x + y
    return &z
}

This version returns a pointer to the local sum, which escapes to the heap. section 12.5.1

BenchmarkSumValue-4   992800992    1.261 ns/op   0 B/op   0 allocs/op
BenchmarkSumPtr-4     82829653     14.84 ns/op   8 B/op   1 allocs/op

With inlining disabled, the pointer benchmark reports one heap allocation per operation and is about an order of magnitude slower in this run. These results are contextual, not a rule that pointers are always slower. section 12.5.1

Use b.ReportAllocs() in benchmarks to report heap allocations; stack allocations are not counted. Run go build -gcflags "-m=2" to inspect compiler escape decisions. Choose values or pointers for semantics and readability first, then optimize allocations where measurements justify it. section 12.5.1 section 12.5.2 section 12.0

When allocation is a measured concern, consider the context before choosing a reduction:

  • Design APIs to avoid unnecessary sharing up; rely on compiler optimizations where applicable. section 12.11 section 12.5.2
  • Preallocate slices and maps when their lengths are known; use strings.Builder for concatenation or avoid unnecessary byte-slice-to-string conversions. section 12.6
  • Consider struct field ordering to reduce size, or sync.Pool as another allocation-reduction tool. section 12.11 section 12.6

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains stack and heap behavior, escape analysis, benchmark results, compiler diagnostics, and several allocation-reduction approaches.
Examples
Compares value-returning and pointer-returning sum functions with inlining disabled and reports benchmark allocation counts.
What you can do after
Diagnose allocation behavior using Go benchmarks and compiler escape reports, then evaluate possible reductions.
How it connects
Connects allocation to garbage collection, escape analysis, struct alignment, and benchmarking.

Also explained in

Compare how 12 books explain memory allocation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.