go build -gcflags="-l -m" -o main main.go
#Delete the file
rm main
Copy the code
Key points:
// 1. The space allocated on the stack will not escape, and the function will be returned after the end // 2. 3. Escape analysis is done at compile time to determine whether objects are allocated to the heap or stackCopy the code
Escape caused by closure
Memory originally allocated on the stack space of a function is used outside the scope of the function due to closures
package main
func closure(a) func(a) int {
var a int
return func(a) int {
a++
return a
}
}
Copy the code
Returns a pointer to a stack variable
The returned variable is a pointer to the stack object that the compiler thinks is needed after the function ends
package main
type Empty struct {}
func Demo(a) *Empty {
return &Empty{}
}
func main(a){}Copy the code
Request escape caused by large object
Too much space is requested, and space is allocated directly on the heap
package main
func bigObj(a) []int {
return make([]int.10000+1)}func main(a) {
_ = bigObj()
}
Copy the code
Apply for variable-length space caused by escape
The compiler has no way of knowing how much space to allocate, since ln is a mutable variable
package main
func allocateVar(ln int) []int {
return make([]int, ln)
}
func main(a){}Copy the code
Returns the escape caused by a locally referenced slice
The compiler thinks that the returned object may be used again after the function call is complete so the compiler allocates memory on the heap
package main
func returnSlice(a) [] int {
return make([]int.10)}func main(a){_ =make(map[string]struct{})}Copy the code
Returns the escape caused by a locally referenced map
The compiler thinks that the returned object may be used again after the function call is complete so the compiler allocates memory on the heap
package main
func returnMap(a) map[string] struct {} {
return make(map[string]struct{})}func main(a){}Copy the code
Escape caused by return function
package main
import "fmt"
func escapeFunction(a) func(a) func(a) {
return func(a) func(a) {
return func(a) {
fmt.Println("hello closure function")}}}var (
_ = escapeFunction
)
func main(a){}Copy the code
conclusion
- Escape caused by closure
- Returns a pointer to a stack variable
- Request escape caused by large object
- Apply for variable-length space caused by escape
- Returns the escape caused by a locally referenced slice
- Returns the escape caused by a locally referenced map
- Escape caused by return function
- Escape is done at compile time by deciding whether to allocate memory on the stack or in the heap
The source code 🦀