Golang闭包会导致内存泄漏吗?

huangapple go评论77阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2022年2月9日 14:00:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/71044678.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定