Allocating on the Stack
5 hours ago
- #performance optimization
- #memory allocation
- #Go programming
- Go programs aim to reduce heap allocations to improve performance and reduce garbage collector overhead.
- Stack allocations are cheaper, cache-friendly, and do not burden the garbage collector.
- Constant-sized slices can be stack-allocated if their size is known at compile time.
- Variable-sized slices in Go 1.25 can use a small stack-allocated backing store if the size is small enough.
- Go 1.26 optimizes append operations by using stack-allocated backing stores for small slices, reducing heap allocations.
- For escaping slices, Go 1.26 introduces `runtime.move2heap` to handle stack-to-heap transitions efficiently.
- Hand optimizations are still beneficial, but the compiler now handles many common cases automatically.
- Optimizations can be disabled with `-gcflags=all=-d=variablemakehash=n` if they cause issues.