Radar · Go · Archive · Week 9 · Feb 23 – Mar 1, 2026
Allocating on the Stack
Worth knowingruntime
- What changed
- The compiler now performs additional analyses to move more allocations from the heap onto the stack.
- Production impact
- The source does not say.
- Try it
- Write a small program that allocates a large struct in a function and print its address to see whether it escapes to the heap.
- Source
- go.dev/blog/allocation-optimizations
Understand it, then run it
The Go compiler now moves more memory allocations from the heap onto the stack. When a program creates a slice and keeps adding elements, the usual pattern is to let append grow the backing array. Each time the array is full, append allocates a larger array on the heap, copies the old data, and discards the old array. That extra work slows the program and increases garbage‑collector load. With the new optimization, if the compiler can prove that the slice will never escape the current function, it may allocate a small temporary backing array on the stack instead of the heap. The first few append calls then use that stack array, avoiding heap allocations entirely. If the slice grows beyond the small stack buffer, the compiler falls back to the normal heap allocation strategy. The result is fewer heap allocations and less garbage‑collector work for many common patterns.
Run it now
// This program demonstrates the stack allocation optimization.
// It builds a slice of 10 integers from a channel and passes it to processAll.
// In Go 1.26+, the backing array is allocated on the stack, so no heap allocation occurs.
package main
import (
"fmt"
)
func processAll(xs []int) {
fmt.Println("Processing", len(xs), "items:", xs)
}
func main() {
c := make(chan int, 10)
for i := 0; i < 10; i++ {
c <- i
}
close(c)
var tasks []int
for v := range c {
tasks = append(tasks, v)
}
processAll(tasks)
}
What it printed when we ran it on Go 1.27.1
Processing 10 items: [0 1 2 3 4 5 6 7 8 9]
Run sends this program (for Solidity, the contract and its tests) to our own sandbox, where it is compiled and run once, with no network, and what it printed or the test report comes back here. Nothing is kept. Runs are counted per visitor for the day so everyone gets a turn; the details are on the legal page.
Written by gpt-oss-20b from the linked source · claims checked against the sources · archive, not individually reviewed