首次提交:初始化项目代码

This commit is contained in:
sunct
2026-07-31 15:18:32 +08:00
commit d6393266b0
193 changed files with 14287 additions and 0 deletions
+40
View File
@@ -0,0 +1,40 @@
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)
}