Files
bulma/gc_escape_avoid.go

41 lines
853 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"fmt"
"runtime"
)
// badFunc 局部大对象返回,触发逃逸
func badFunc() []byte {
buf := make([]byte, 1024*1024) // 1MB对象
return buf
}
// goodFunc 接收外部切片,复用内存,避免逃逸
func goodFunc(buf []byte) {
for i := range buf {
buf[i] = byte(i % 256)
}
}
func main() {
var stats runtime.MemStats
// 测试逃逸场景
runtime.GC()
for i := 0; i < 50; i++ {
_ = badFunc()
}
runtime.ReadMemStats(&stats)
fmt.Printf("逃逸场景:堆分配%d MBGC次数%d\n", stats.HeapAlloc/1024/1024, stats.NumGC)
// 测试避免逃逸场景
runtime.GC()
buf := make([]byte, 1024*1024) // 一次分配,复用
for i := 0; i < 50; i++ {
goodFunc(buf)
}
runtime.ReadMemStats(&stats)
fmt.Printf("避免逃逸:堆分配%d MBGC次数%d\n", stats.HeapAlloc/1024/1024, stats.NumGC)
}