英文:
will golang closure memory leak?
问题
让我们假设我有这个闭包函数:
package main
type A struct {
Name string
}
func main() {
s := func(name string) *A {
return &A{
Name: name,
}
}("checkmate")
s.Name = "bbb"
}
我已经使用基准测试和gcflags进行了测试,以下是结果:
cpu: Intel(R) Core(TM) i3-10110U CPU @ 2.10GHz
BenchmarkMain-4 1000000000 0.4877 ns/op 0 B/op 0 allocs/op
执行go build -gcflags "-m"
命令后,得到以下输出:
./main.go:8:7: can inline main.func1
./main.go:7:6: can inline main
./main.go:12:3: inlining call to main.func1
./main.go:12:3: &A{...} does not escape
这段代码是否仍然是内存安全的?或者我在内存分配检查方面是否遗漏了什么?
英文:
let's say i have this closure func
package main
type A struct {
Name string
}
func main() {
s := func(name string) *A {
return &A{
Name: name,
}
}("checkmate")
s.Name = "bbb"
}
i have tested with benchmark and gcflags and this is the result
cpu: Intel(R) Core(TM) i3-10110U CPU @ 2.10GHz
BenchmarkMain-4 1000000000 0.4877 ns/op 0 B/op 0 allocs/op
go build -gcflags "-m"
./main.go:8:7: can inline main.func1
./main.go:7:6: can inline main
./main.go:12:3: inlining call to main.func1
./main.go:12:3: &A{...} does not escape
is this still memory safe? or maybe there's something missing for my memory allocation check?
答案1
得分: 0
不,闭包不会泄漏内存。
英文:
No, closures do not leak memory.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论