NOTE
3.2 Escape Analysis
How Go uses escape analysis to decide whether values created with new are allocated on the heap or stack, why escape analysis matters, and a compiler-output example.
This is a historical learning note and may contain outdated or incomplete understanding.
1. Escape Analysis
Objects created in Java or C++ are generally allocated on the heap, while objects created with new in Golang are allocated on the heap or stack according to escape analysis.
2. Why Escape Analysis Is Needed
| Heap | Stack | |
|---|---|---|
| Reclamation | Requires garbage collection | Destroyed when the function exits |
| Space | Large | Small |
3. How Escape Analysis Works
If there is no reference outside the function, prefer placing it on the stack;
If there is a reference outside the function, it must be placed on the heap.
4. Example
package main
import "fmt"
func foo() *int {
t := 3
return &t;
}
func main() {
x := foo()
fmt.Println(*x)
}
go build -gcflags '-m -l' main.go
# command-line-arguments
// t escaped; no problem
.\main.go:6:2: moved to heap: t
.\main.go:12:13: main ... argument does not escape
// Did x also escape? When a function parameter is an interface type, such as fmt.Println(a ...interface{}), it is difficult to determine the concrete parameter type during compilation, so escape can also occur
.\main.go:12:14: *x escapes to heap
go tool compile -S test.go | grep -i "test.go:6"
0x0024 00036 (test.go:6) PCDATA $0, $1
0x0024 00036 (test.go:6) PCDATA $1, $0
0x0024 00036 (test.go:6) LEAQ type.int(SB), AX
0x002b 00043 (test.go:6) PCDATA $0, $0
0x002b 00043 (test.go:6) MOVQ AX, (SP)
0x002f 00047 (test.go:6) CALL runtime.newobject(SB)// newobject shows that x escaped
0x0034 00052 (test.go:6) PCDATA $0, $1
0x0034 00052 (test.go:6) MOVQ 8(SP), AX
0x0039 00057 (test.go:6) MOVQ $3, (AX)
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub