gooptimizationcompilation

cmd/compile: The mechanism by which stack-allocated variable memory within a loop is reused


I have a question about Go optimization.

In Go, even if a variable is declared within a loop, if it does not escape to the heap, the same stack address is reused across iterations instead of allocating a new memory address each time. After escape analysis determines whether a variable escapes, where in cmd/compile is this optimization performed?

Could you please help me with this question?

package main

func main() {
    for i := 0; i < 3; i++ {
        var x int
        println(&x) // output same address
    }
}

Solution

  • Your variable does not escape: The pointer to x does not survive the loop scope, so x can be allocated on the stack and reused by code generation. Note that this is not in the AST, but probably done in the live detection in the stackalloc SSA backend.