funcAppend(slice, data []byte) []byte {
l :=len(slice)
if l +len(data) > cap(slice) { // reallocate// Allocate double what's needed, for future growth. newSlice :=make([]byte, (l+len(data))*2)
// The copy function is predeclared and works for any slice type.copy(newSlice, slice)
slice = newSlice
}
slice = slice[0:l+len(data)]
copy(slice[l:], data)
return slice
}
$ go build -gcflags "-m -m" q.go# command-line-arguments
./q.go:7:6: cannot inline main: non-leaf function
./q.go:14:13: s1 escapes to heap
./q.go:14:13: from ...argument (arg to ...) at ./q.go:14:13./q.go:14:13: from *(... argument) (indirection) at ./q.go:14:13./q.go:14:13: from ...argument (passed to call[argument content escapes]) at ./q.go:14:13./q.go:8:13: ([]byte)("") escapes to heap
./q.go:8:13: from s (assigned) at ./q.go:8:4./q.go:8:13: from s1 (assigned) at ./q.go:11:5./q.go:8:13: from s1 (interface-converted) at ./q.go:14:13./q.go:8:13: from ...argument (arg to ...) at ./q.go:14:13./q.go:8:13: from *(... argument) (indirection) at ./q.go:14:13./q.go:8:13: from ...argument (passed to call[argument content escapes]) at ./q.go:14:13
以上输出中的 s1 escapes to heap 和 ([]byte)("") escapes to heap 表明,由于 fmt.Println(s1, "===", s2) 代码的引入导致了变量分配模型的变化。简单点讲就是从栈中逃逸到了堆上。内存逃逸的分析我们会在后面的章节详细介绍。问题到此,大概的思路已经有了,但是我们如何通过代码层面进行验证呢? 通过搜索 go 源码实现调用的函数 runtime.stringtoslicebyte 的地方进行入手。通过搜索发现调用的文件在 cmd/compile/internal/gc/walk.go
case OSTRARRAYBYTE:
a :=nodnil() // 分配到堆上的的默认行为if n.Esc == EscNone {
// Create temporary buffer for slice on stack. t := types.NewArray(types.Types[TUINT8], tmpstringbufsize)
a = nod(OADDR, temp(t), nil) // 分配在栈上,大小为32 }
n = mkcall("stringtoslicebyte", n.Type, init, a, conv(n.Left, types.Types[TSTRING]))
Go 语言能够自动进行内存管理,避免了 C 语言中的内存自己管理的麻烦,但是同时对于代码的内存管理和回收细节进行了封装,也潜在增加了系统调试和优化的难度。同时,内存自动管理也是一项非常困难的事情,比如函数的多层调用、闭包调用、结构体或者管道的多次赋值、切片和MAP、CGO调用等多种情况综合下,往往会导致自动管理优化机制失效,退化成原始的管理状态;go 中的内存回收(GC)策略也在不断地优化过程。Golang 从第一个版本以来,GC 一直是大家诟病最多的,但是每一个版本的发布基本都伴随着 GC 的改进。下面列出一些比较重要的改动。
package main
import"fmt"funcmain() {
x :=42 fmt.Println(x)
}
go build 工具中的 flag -gcflags '-m' 可以用来分析内存逃逸的情况汇总,最多可以提供 4 个 “-m”, m 越多则表示分析的程度越详细,一般情况下我们可以采用两个 m 分析。
bash
1
2
3
4
5
6
7
8
9
10
11
12
13
$ go build -gcflags '-m -l' 2.go
# command-line-arguments./2.go:7:13: x escapes to heap
./2.go:7:13: main ... argument does not escape
# -l disable inline, 也可以调用的函数前添加注释 $ go build -gcflags '-m -m -l' 2.go
# command-line-arguments./2.go:7:13: x escapes to heap
./2.go:7:13: from ... argument (arg to ...) at ./2.go:7:13
./2.go:7:13: from *(... argument)(indirection) at ./2.go:7:13
./2.go:7:13: from ... argument (passed to call[argument content escapes]) at ./2.go:7:13
./2.go:7:13: main ... argument does not escape
上例中的 x escapes to heap 则表明了变量 x 变量逃逸到了堆(heap)上。其中 -l 表示不启用 inline 模式调用,否则会使得分析更加复杂,也可以在函数上方添加注释 //go:noinline禁止函数 inline调用。至于调用 fmt.Println()为什么会导致 x escapes to heap,可以参考 Issue #19720 和 Issue #8618,对于上述 fmt.Println() 的行为我们可以通过以下代码进行简单模拟测试,效果基本一样:
package main
type pp struct {
arg interface{}
}
funcMyPrintln(a ...interface{}) {
Fprintln(a...)
}
funcFprintln(a ...interface{}) (n int, err error) {
pp :=new(pp)
pp.arg = a // 此处导致了内存的逃逸return}
funcmain() {
x :=42MyPrintln(x)
}
内存逃逸分析结果如下:
bash
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$ go build -gcflags '-m -m -l' 3.go
# command-line-arguments./3.go:13:9: a escapes to heap
./3.go:13:9: from pp.arg (star-dot-equals) at ./3.go:13:9
./3.go:11:45: leaking param: a
./3.go:11:45: from a (interface-converted) at ./3.go:13:9
./3.go:11:45: from pp.arg (star-dot-equals) at ./3.go:13:9
./3.go:12:11: Fprintln new(pp) does not escape
./3.go:7:21: leaking param: a
./3.go:7:21: from a (passed to call[argument escapes]) at ./3.go:8:10
./3.go:19:11: ... argument escapes to heap
./3.go:19:11: from ... argument (passed to call[argument escapes]) at ./3.go:19:11
./3.go:19:11: x escapes to heap
./3.go:19:11: from ... argument (arg to ...) at ./3.go:19:11
./3.go:19:11: from ... argument (passed to call[argument escapes]) at ./3.go:19:11
主要原因如下:变量 x 虽为 int 类型,但是在传递给函数 MyPrintln函数中被转换成 interface{} 类型,因为 interface{} 类型中包含指向数据的地址,因此 x 在传递到函数 MyPrintln过程中进行了一个内存重新分配的过程,由于 pp.arg = a 结构体中的字段赋值的引用,导致了后续变量的逃逸到了堆上。如果将上述 pp.arg = a 注释掉,则不会出现内存逃逸的情况。
package main
// go build -gcflags '-m -m -l' 5.gotype S struct {
s1 int}
func (s *S) M1(i int) { s.s1 = i }
type I interface {
M1(int)
}
funcmain() {
var s1 S // this escapesvar s2 S // this does notf1(&s1)
f2(&s2)
}
funcf1(s I) { s.M1(42) }
funcf2(s *S) { s.M1(42) }
逃逸分析确认:
bash
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
go build -gcflags '-m -m -l' 5.go
# command-line-arguments./5.go:9:18: (*S).M1 s does not escape
./5.go:23:11: leaking param: s
./5.go:23:11: from s.M1(42)(receiver in indirect call) at ./5.go:23:21
./5.go:24:12: f2 s does not escape
./5.go:19:5: &s1 escapes to heap
./5.go:19:5: from &s1 (passed to call[argument escapes]) at ./5.go:19:4
./5.go:19:5: &s1 escapes to heap
./5.go:19:5: from &s1 (interface-converted) at ./5.go:19:5
./5.go:19:5: from &s1 (passed to call[argument escapes]) at ./5.go:19:4
./5.go:16:6: moved to heap: s1
./5.go:20:5: main &s2 does not escape
<autogenerated>:1:0: leaking param: .this
<autogenerated>:1:0: from .this.M1(.anon0)(receiver in indirect call) at <autogenerated>:1:0
package main_test
import"testing"// go test -bench . --benchmem -gcflags "-N -l" 5_test.gotype S struct {
s1 int}
func (s *S) M1(i int) {
s.s1 = i
}
type I interface {
M1(int)
}
funcf1(s I) { s.M1(86) }
funcf2(s *S) { s.M1(86) }
funcBenchmarkTestInterface(b *testing.B) {
var s1 S
for i :=0; i < b.N; i++ {
f1(&s1)
}
}
funcBenchmarkTestNoInterface(b *testing.B) {
var s2 S
for i :=0; i < b.N; i++ {
f2(&s2)
}
}
禁止使用 inline 方式的函数调用性能报告:
bash
1
2
3
4
5
6
7
8
# 禁止使用 inline$ go test -bench . --benchmem -gcflags "-N -l" 5_test.go
goos: darwin
goarch: amd64
BenchmarkTestInterface-8 300000000 4.50 ns/op 0 B/op 0 allocs/op
BenchmarkTestNoInterface-8 500000000 3.80 ns/op 0 B/op 0 allocs/op
PASS
ok command-line-arguments 4.094s
启用了 inline 方式的函数调用性能报告:
bash
1
2
3
4
5
6
7
8
# 如果启用了 inline,性能差别非常明显$ go test -bench . --benchmem 5_test.go
goos: darwin
goarch: amd64
BenchmarkTestInterface-8 500000000 3.45 ns/op 0 B/op 0 allocs/op
BenchmarkTestNoInterface-8 2000000000 0.29 ns/op 0 B/op 0 allocs/op
PASS
ok command-line-arguments 2.685s
package main
funcmain() {
s :=make([]byte, 1, 1*1024)
_ = s
}
$ go build -gcflags "-m -m" slice_esc.go# command-line-arguments
./slice_esc.go:3:6: can inline main as: func() { s :=make([]byte, 1, 1*1024); _ = s }
./slice_esc.go:4:11: main make([]byte, 1, 1*1024) does not escape
如果 slice 大小超过 64k,则会分配到堆上 (go 1.9.2)
go
1
2
3
4
5
6
7
8
9
10
11
package main
funcmain() {
s :=make([]byte, 1, 64*1024) // 64k _ = s
}
$ go build -gcflags "-m -m" slice_esc.go# command-line-arguments
./slice_esc.go:3:6: can inline main as: func() { s :=make([]byte, 1, 64*1024); _ = s }
./slice_esc.go:4:11: make([]byte, 1, 64*1024) escapes to heap
./slice_esc.go:4:11: from make([]byte, 1, 64*1024) (too large for stack) at ./slice_esc.go:4:11
指针类型切片验证
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package main
funcmain() {
s :=make([]*string, 1, 100)
str :="hello" s = append(s, &str)
_ = s
}
$ go build -gcflags "-m -m -l" slice_esc.go# command-line-arguments
./slice_esc.go:6:16: &str escapes to heap
./slice_esc.go:6:16: from append(s, &str) (appended to slice) at ./slice_esc.go:6:12./slice_esc.go:5:9: moved to heap: str
./slice_esc.go:4:11: main make([]*string, 1, 100) does not escape
对于保存在 []*string 中的字符串都会直接在堆上分配。
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package main
import"math/rand"funcmain() {
randSize := rand.Int()
s :=make([]*string, 0, randSize)
str :="hello" s = append(s, &str)
_ = s
}
$ go build -gcflags "-m -m -l" slice_esc.go# command-line-arguments
./slice_esc.go:7:11: make([]*string, 0, randSize) escapes to heap
./slice_esc.go:7:11: from make([]*string, 0, randSize) (too large for stack) at ./slice_esc.go:7:11./slice_esc.go:9:16: &str escapes to heap
./slice_esc.go:9:16: from append(s, &str) (appended to slice) at ./slice_esc.go:9:12./slice_esc.go:8:9: moved to heap: str
由于 s := make([]*string, 0, randSize) 大小不能编译确定,所以会逃逸到堆上。
评论