Runtime and memory · 3 MIN READ

Stacks, escape analysis and object lifetimes

Explain why returning a local address is safe and why allocation placement must be measured.

Lifetime is the semantic question: how long must a value remain usable? Stack and heap placement are implementation choices used to satisfy that requirement. The compiler performs escape analysis; source syntax alone is not a dependable allocation profiler.

01

A local address can safely leave a function

Returning a pointer to a local value is normal Go. The implementation arranges storage so callers do not receive a dangling pointer. Do not import C stack-lifetime rules into this code.

go
type Counter struct { N int }
func newCounter() *Counter {
    c := Counter{N: 1}
    return &c
}
Read the code

The local spelling c does not disappear in a way that invalidates the returned pointer. Exactly which allocations survive optimization can depend on inlining and the surrounding call sites.

02

Pointers are a design decision first

A value receiver copies its receiver; a pointer receiver allows shared mutation and may be required by method sets. Neither form is universally faster. Large copies, escaping references, cache locality and synchronization all matter. Start with ownership and API semantics, then inspect a benchmark that represents the actual use.

03

Inspect the native build, not an assumption

On a desktop Go installation, compiler diagnostics can report escape decisions. Their wording and decisions can change across versions; they are observations, not API guarantees.

shell
go build -gcflags="-m=2" ./...
go test -bench=. -benchmem ./...
Read the code

Use these commands in your development environment. Compare allocations per operation and time after warm-up. The app's WebAssembly sandbox does not reproduce every native service allocation or threading cost.

TAKE THIS WITH YOU

Reason about required lifetime first. Use compiler diagnostics and measurements to learn how the implementation realizes it.

Check your understanding

Which statement is correct about escape analysis?

Go to the source

Progress stays in this browser. No account needed.