欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

我如何在 Go - 命令行参数中实现 5 倍的性能提升

最编程 2024-04-08 10:37:16
...

./main.go:26:21: inlining call to reflect.ValueOf ./main.go:26:21: inlining call to reflect.escapes ./main.go:26:21: inlining call to reflect.unpackEface ./main.go:26:21: inlining call to reflect.(*rtype).Kind ./main.go:26:21: inlining call to reflect.ifaceIndir ./main.go:26:22: x escapes to heap 需要注意,逃逸的检测是通过-gcflags=-m,一般还需要关闭内联比如-gcflags="-m -l"。

类型的选择:强类型 vs interface 为降低可能的空间分配、拷贝,建议只在必要情况下使用 interface、reflect。

针对函数定义中强类型、interface 的性能对比,测试如下:

type testStruct struct { Data [8192]byte }

func StrongType(t testStruct) { t.Data[0] = 1 }

func InterfaceType(ti interface{}) { ts := ti.(testStruct) ts.Data[0] = 1 }

func BenchmarkTypeStrong(b *testing.B) { t := testStruct{} t.Data[0] = 2 for i := 0; i < b.N; i++ { StrongType(t) } }

func BenchmarkTypeInterface(b *testing.B) { t := testStruct{} t.Data[0] = 2 for i := 0; i < b.N; i++ { InterfaceType(t) } } 会导致逃逸时(sizeof(testStruct.Dat)==8192):

➜ test go test -bench='Type' -run=none -benchmem goos: darwin goarch: amd64 pkg: gotest666/test cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz BenchmarkTypeStrong-12 1000000000 0.2546 ns/op 0 B/op 0 allocs/op BenchmarkTypeInterface-12 799846 1399 ns/op 8192 B/op 1 allocs/op PASS 没有逃逸时(sizeof(testStruct.Dat)==1):

➜ test go test -bench='Type' -run=none -benchmem goos: darwin goarch: amd64 pkg: gotest666/test cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz BenchmarkTypeStrong-12 1000000000 0.2549 ns/op 0 B/op 0 allocs/op BenchmarkTypeInterface-12 1000000000 0.2534 ns/op 0 B/op 0 allocs/op PASS 在一些会导致逃逸的情况下,不建议使用 Interface。 目前一些可能会导致逃逸的函数:

类型转换: 强转 vs 断言 vs reflect 目前 Go 中数据类型转换,存在以下几种方式:

强转,如 int 转 int64,可用 int64(intData)。强转是对底层数据进行语意上的重新解释; interface 的断言,根据已有信息,对变量类型进行断言,如 interfaceData.(int64),会利用 type 中相关信息,对类型进行校验、转换; reflect 相关函数,如 reflect.Valueof(intData).Int(),其中 intData 可以为各种 int 相关类型,具有非常好的灵活性。 针对此的测试如下:

type testStruct struct { Data [8192]byte }

func BenchmarkConvertForce(b *testing.B) { for i := 0; i < b.N; i++ { var v = int32(64) f := int64(v) if f != int64(64) { b.Error("errror") } } }

func BenchmarkConvertReflect(b *testing.B) { for i := 0; i < b.N; i++ { var v = int32(64) f := reflect.ValueOf(v).Int() if f != int64(64) { b.Error("errror") } } }

func BenchmarkConvertAssert(b *testing.B) { for i := 0; i < b.N; i++ { var v interface{} = int32(64) f := v.(int32) if f != int32(64) { b.Error("error") } } }

func BenchmarkConvertBigReflect(b *testing.B) { for i := 0; i < b.N; i++ { f := reflect.ValueOf(testStruct{}).Interface().(testStruct) if len(f.Data) <= 0 { b.Error("errror") } } }

func BenchmarkConvertBigAssert(b *testing.B) { for i := 0; i < b.N; i++ { var v interface{} = testStruct{} f := v.(testStruct) if len(f.Data) <= 0 { b.Error("error") } } } ➜ test go test -bench='Convert' -run=none -benchmem goos: darwin goarch: amd64 pkg: gotest666/test cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz BenchmarkConvertForce-12 1000000000 0.2561 ns/op 0 B/op 0 allocs/op BenchmarkConvertReflect-12 259114099 3.892 ns/op 0 B/op 0 allocs/op BenchmarkConvertAssert-12 1000000000 0.5068 ns/op 0 B/op 0 allocs/op BenchmarkConvertBigReflect-12 759171 1595 ns/op 8192 B/op 1 allocs/op BenchmarkConvertBigAssert-12 827790 1593 ns/op 8192 B/op 1 allocs/op 性能上:强类型转换/assert > reflect。 3.2 常用 map Go 中常用的 map 包含,runtime.map、sync.map 和第三方的 ConcurrentMap。

Go 中 map 的定义位于 map.go,是基于 bucket 的 map的实现,如下:

type hmap struct { ...... B uint8 // buckets中桶的数目为2的B次方个 hash0 uint32 // hash seed

buckets    unsafe.Pointer // bucket实现
oldbuckets unsafe.Pointer // 旧bucket,主要用于rehash的渐渐式迁移
......

} 其结构如下:

sync.map 定义位于 map.go 中,其是典型的以空间换时间的处理,其以通过 readonly 实现了冗余读,具体如下:

type readOnly struct { m map[interface{}]*entry amended bool // true if the dirty map contains some key not in m. }

type entry struct { p unsafe.Pointer // *interface{} }

type Map struct { mu Mutex read atomic.Value // readOnly数据 dirty map[interface{}]*entry misses int } read 中存储的是 dirty 数据的一个指针副本,在读多写少的情况下,可以实现无锁的数据读取,以读取为例其处理逻辑如下:

func (m *Map) Load(key any) (value any, ok bool) { read, _ := m.read.Load().(readOnly) e, ok := read.m[key] if !ok && read.amended { m.mu.Lock() // double check read, _ = m.read.Load().(readOnly) e, ok = read.m[key] if !ok && read.amended { // 从dirty查询 e, ok = m.dirty[key] m.missLocked() } m.mu.Unlock() } if !ok { return nil, false } return e.load() } ConcurrentMap,其采用分段锁的原理,通过降低锁的粒度提升性能,参见:current-map。

针对 map、sync.map、ConcurrentMap 的测试如下:

const mapCnt = 20 func BenchmarkStdMapGetSet(b *testing.B) { mp := map[string]string{} keys := []string{"a", "b", "c", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r"} for i := range keys { mp[keys[i]] = keys[i] } var m sync.Mutex b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { for i := 0; i < mapCnt; i++ { for j := range keys { m.Lock() _ = mp[keys[j]] m.Unlock() } }

        m.Lock()
        mp["d"] = "d"
        m.Unlock()
    }
})

}

func BenchmarkSyncMapGetSet(b *testing.B) { var mp sync.Map keys := []string{"a", "b", "c", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r"} for i := range keys { mp.Store(keys[i], keys[i]) } b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { for i := 0; i < mapCnt; i++ { for j := range keys { _, _ = mp.Load(keys[j]) } }

        mp.Store("d", "d")
    }
})

}

func BenchmarkConcurrentMapGetSet(b *testing.B) { m := cmap.Newstring keys := []string{"a", "b", "c", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r"} for i := range keys { m.Set(keys[i], keys[i]) } b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { for i := 0; i < mapCnt; i++ { for j := range keys { _, _ = m.Get(keys[j]) } }

        m.Set("d", "d")
    }
})

} 读写操作比,20:20

➜ test go test -bench='GetSet' -run=none -benchmem goos: darwin goarch: amd64 pkg: gotest666/test cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz BenchmarkStdMapGetSet-12 44818 29318 ns/op 0 B/op 0 allocs/op BenchmarkSyncMapGetSet-12 159310 8013 ns/op 320 B/op 20 allocs/op BenchmarkConcurrentMapGetSet-12 155390 8032 ns/op 0 B/op 0 allocs/op 读写操作比,1:20

➜ test go test -bench='GetSet' -run=none -benchmem goos: darwin goarch: amd64 pkg: gotest666/test cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz BenchmarkStdMapGetSet-12 466243 2553 ns/op 0 B/op 0 allocs/op BenchmarkSyncMapGetSet-12 255799 4657 ns/op 320 B/op 20 allocs/op BenchmarkConcurrentMapGetSet-12 414024 2721 ns/op 0 B/op 0 allocs/op 读写操作比,20:1

➜ test go test --bench='GetSet' -run=none -benchmem goos: darwin goarch: amd64 pkg: gotest666/test cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz BenchmarkStdMapGetSet-12 49065 24976 ns/op 0 B/op 0 allocs/op BenchmarkSyncMapGetSet-12 722704 1756 ns/op 16 B/op 1 allocs/op BenchmarkConcurrentMapGetSet-12 227001 5206 ns/op 0 B/op 0 allocs/op PASS 读>>写时,建议用 sync.Map。写>>读时,建议用 runtime.map。读=写时,建议用 courrentMap 3.3 hash 的实现: index vs map 在使用到 hash 的场景,除了 map,我们还可以基于 slice 或者数组索引的方式实现另外一种 map,即把 index 当做 key、value 当做 hash 的值,如下。

其性能对比如下:

func BenchmarkHashIdx(b *testing.B) { var data = [10]int{0: 1, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9} for i := 0; i < b.N; i++ { tmp := data[b.N%10] _ = tmp } } func BenchmarkHashMap(b *testing.B) { var data = map[int]int{0: 1, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9} for i := 0; i < b.N; i++ { tmp := data[b.N%10] _ = tmp } } ➜ test go test --bench='Hash' -run=none -benchmem goos: darwin goarch: amd64 pkg: gotest666/test cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz BenchmarkHashIdx-12 1000000000 1.003 ns/op 0 B/op 0 allocs/op BenchmarkHashMap-12 196543544 7.665 ns/op 0 B/op 0 allocs/op PASS 可见其性能会有5倍左右提升。

3.4 string 和 slice string 和 slice 的定义 Go 中 string、slice 都是基于 buf、len 的元组的定义,二者定义都位于 value.go 中:

type StringHeader struct Data uintptr Len int }

type SliceHeader struct { Data uintptr Len int Cap int } 通过二者定义可以得出:

在值拷贝背景下,string、slice 的赋值操作代价都不大; slice 因为涉及到 cap,会涉及到预分配、惰性删除,其具体位于 slice.go。 String、[]byte 转换

Go 中 string 和 []byte 间相互转换包含2种:

采用原生机制,比如string转slice可采用,[]byte(strData)或者string(byteData); 基于二者数据结构,对底层数据重新解释。 以 string 转换为 byte 为例,原生转换的转换会进行如下操作,其位于 string.go 中:

func stringtoslicebyte(buf *tmpBuf, s string) []byte { var b []byte if buf != nil && len(s) <= len(buf) { // 如果可以在tmpBuf中保存 *buf = tmpBuf{} b = buf[:len(s)] } else { b = rawbyteslice(len(s)) // 如果32字节不够存储数据,则调用mallocgc分配空间 } copy(b, s) // 数据拷贝 return b }

// rawbyteslice allocates a new byte slice. The byte slice is not zeroed. func rawbyteslice(size int) (b []byte) { cap := roundupsize(uintptr(size)) p := mallocgc(cap, nil, false) // 空间分配 if cap != uintptr(size) { memclrNoHeapPointers(add(p, uintptr(size)), cap-uintptr(size)) }

*(*slice)(unsafe.Pointer(&b)) = slice{p, size, int(cap)}

return } 其中 tmpBuf 定义为 type tmpBuf [32]byte。可见当 string 长度超过32字节时,会进行空间的分配、拷贝。 同理,byte 转换为 string,原生处理位于 slicebytetostring 函数,也位于 string.go 中。

针对多余的空间分配、拷贝问题,我们对其进行了封装,该实现通过对底层数据重新解释进行,具有较高的效率。

相关封装、ByteToString 性能对比如下:

// 对底层数据进行重新解释 func Bytes2String(b []byte) string { x := (*[3]uintptr)(unsafe.Pointer(&b)) s := [2]uintptr{x[0], x[1]} return *(*string)(unsafe.Pointer(&s)) }

func String2Bytes(s string) []byte { x := (*[2]uintptr)(unsafe.Pointer(&s)) b := [3]uintptr{x[0], x[1], x[1]} return ([]byte)(unsafe.Pointer(&b)) }

func BenchmarkByteToStringRaw(b *testing.B) { bytes := getByte(34) b.ResetTimer() for i := 0; i < b.N; i++ { v := string(bytes) if len(v) <= 0 { b.Error("error") } } }

func BenchmarkByteToStringPointer(b *testing.B) { bytes := getByte(34) b.ResetTimer() for i := 0; i < b.N; i++ { v := Bytes2String(bytes) if len(v) <= 0 { b.Error("error") } } } ➜ gotest666 go test --bench='ByteToString' -run=none -benchmem goos: darwin goarch: amd64 pkg: gotest666 cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz BenchmarkByteToStringRaw-12 47646651 23.37 ns/op 48 B/op 1 allocs/op BenchmarkByteToStringPointer-12 1000000000 0.7539 ns/op 0 B/op 0 allocs/op 其性能提升的主要原因,0gc 0拷贝 需要注意,本处理只针对转换,不涉及 append 等可能引起扩容的处理。 string 的拼接

当前 Golang 中字符串拼接方式,主要包含:

使用+连接字符串; 使用 fmt.Sprintf; 使用运行时提供的工具类,strings.Builder 或者 bytes.Buffer ; 预分配机制。 目前对+的处理,编译后其处理函数位于 string.go,当要连接的字符串长度>32时,每次会进行空间的分配和拷贝处理,其处理如下:

func concatstrings(buf *tmpBuf, a []string) string { idx := 0 l := 0 count := 0 for i, x := range a { // 计算+链接字符的长度 n := len(x) if n == 0 { continue } if l+n < l { throw("string concatenation too long") } l += n count++ idx = i } if count == 0 { return "" } ..... s, b := rawstringtmp(buf, l) // 如果长度小于len(buf)(32),则分配空间,否则使用buf for _, x := range a { copy(b, x) b = b[len(x):] } return s } 需要注意,tmpBuf 定义 type tmpBuf [32]byte。 fmt.Sprinf,涉及逃逸,也会有大量的空间分配、拷贝。

针对+、fmt.Sprintf 等的性能对比测试如下:

func BenchmarkStringJoinAdd(b *testing.B) { var s string for i := 0; i < b.N; i++ { for i := 0; i < count; i++ { s += "10" } } }

func BenchmarkStringJoinSprintf(b *testing.B) { var s string for i := 0; i < b.N; i++ { for i := 0; i < count; i++ { s = fmt.Sprintf("%s%s", s, "10") } } }

func BenchmarkStringJoinStringBuilder(b *testing.B) { var sb strings.Builder sb.Grow(count * 2) // 预分配了空间 b.ResetTimer()

for i := 0; i < b.N; i++ { for i := 0; i < count; i++ { sb.WriteString("10") } } } ➜ test go test -bench='StringJoin' -run=none -benchmem goos: darwin goarch: amd64 pkg: gotest666/test cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz BenchmarkStringJoinAdd-12 19 864766686 ns/op 7679332420 B/op 20365 allocs/op BenchmarkStringJoinSprintf-12 13 1546112322 ns/op 10474999415 B/op 65459 allocs/op BenchmarkStringJoinStringBuilder-12 10000 205483 ns/op 234915 B/op 0 allocs/op BenchmarkStringJoinStringBuilderPreAlloc-12 21061 139415 ns/op 217885 B/op 0 allocs/op 可以看出,空间预分配拥有最高性能指标。

其他的一些更为详细的测试参见:string连接。

3.5 循环的处理:for vs range Go 中常用的循环有2种 for index 和 for range 如下:

按位置进行遍历,for 和 range 都支持,如 for i:=range a{}, for i:=0;i<len(a);i++。 同时对位置、值进行遍历,仅 range 支持,如 for i,v := range a {}。 Go 中循环经过一系列的编译、优化后,伪代码如下:

ta := a // 容器的拷贝 i := 0 l := len(ta) // 获取长度 for ; i < l; i++ { v := ta[i] // 拷贝容器中元素,仅for range value支持 } 此处理可能会导致以下问题:

遍历前,会进行值的拷贝。如果容器是数组,会有大量数据拷贝,引用类型拷贝较少; for range value 在遍历中存在对容器元素的拷贝; 遍历开始,已经确定了容器长度,中间添加的数据,不会遍历到。 针对此测试如下:

type Item struct { id int val [8192]byte }

func BenchmarkLoopFor(b *testing.B) { var items [1024]Item for i := 0; i < b.N; i++ { length := len(items) var tmp int for k := 0; k < length; k++ { tmp = items[k].id } _ = tmp } }

func BenchmarkLoopRangeIndex(b *testing.B) { var items [1024]Item for i := 0; i < b.N; i++ { var tmp int for k := range items { tmp = items[k].id } _ = tmp } }

func BenchmarkLoopRangeValue(b *testing.B) { var items [1024]Item for i := 0; i < b.N; i++ { var tmp int for _, item := range items { tmp = item.id } _ = tmp } } Sizeof(Item.val)=1

➜ test go test -bench='Loop' -run=none -benchmem goos: darwin goarch: amd64 pkg: gotest666/test cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz BenchmarkLoopFor-12 4370520 273.2 ns/op 0 B/op 0 allocs/op BenchmarkLoopRangeIndex-12 4520882 265.6 ns/op 0 B/op 0 allocs/op BenchmarkLoopRangeValue-12 4293848 303.8 ns/op 0 B/op 0 allocs/op PASS sizeof(Item.val)=8192

➜ test go test --bench='Loop' -run=none -benchmem goos: darwin goarch: amd64 pkg: gotest666/test cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz BenchmarkLoopFor-12 4334842 270.8 ns/op 0 B/op 0 allocs/op BenchmarkLoopRangeIndex-12 4436786 272.7 ns/op 0 B/op 0 allocs/op BenchmarkLoopRangeValue-12 7310 211009 ns/op 0 B/op 0 allocs/op 在需要较大存储空间、元素需要较大存储空间时,建议不要采用 for range value 的方式。 3.6 重载 目前 Go 中重载的实现包含2种,泛型(1.18)、基于 interface 的定义。

泛型的优点在于预编译,即编译期间即可确定类型,对比基于 interface 的逃逸会有一定收益。

具体测试如下:

func AddGeneric[T int | int16 | int32 | int64](a, b T) T { return a + b }

func AddInterface(a, b interface{}) interface{} { switch a.(type) { case int: return a.(int) + b.(int) case int32: return a.(int32) + b.(int32) case int64: return a.(int64) + b.(int64) } return 0 }

func BenchmarkOverLoadGeneric(b *testing.B) { for i := 0; i < b.N; i++ { x := AddGeneric(i, i) _ = x } } func BenchmarkOverLoadInterface(b *testing.B) { for i := 0; i < b.N; i++ { x := AddInterface(i, i) _ = x.(int) } } ➜ test go test --bench='OverLoad' -run=none -benchmem goos: darwin goarch: amd64 pkg: gotest666/test cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz BenchmarkOverLoadGeneric-12 1000000000 0.2778 ns/op 0 B/op 0 allocs/op BenchmarkOverLoadInterface-12 954258690 1.248 ns/op 0 B/op 0 allocs/op PASS 对比 interface 类型的处理,泛型有一定的性能的提升。

0间与布局 在栈上分配空间为什么会比堆上快?

4.1 栈与堆空间的分配 通过汇编,可观察栈空间分配机制,如下:

package main

func test(a, b int) int { return a + b } 其对应汇编代码如下:

main.test STEXT nosplit size=49 args=0x10 locals=0x10 funcid=0x0 align=0x0 0x0000 00000 (/Users/zhangyuxin/go/src/gotest666/test.go:3) TEXT main.test(SB), NOSPLIT|ABIInternal, $16-16 0x0000 00000 (/Users/zhangyuxin/go/src/gotest666/test.go:3) SUBQ $16, SP // 栈扩容 ...... 0x002c 00044 (/Users/zhangyuxin/go/src/gotest666/test.go:4) ADDQ $16, SP // 栈释放 0x0030 00048 (/Users/zhangyuxin/go/src/gotest666/test.go:4) RET Go 中栈的扩容、释放只涉及到了 SUBQ、ADDQ 2 条指令。

对应的基于堆的内存分配,位于 malloc.go 中 mallocgc 函数,p 的定义、mheap 的定义分别位于 runtime2.go、mcache.go、mheap.go,其分配流程具体如下(以<32K, >8B为例):

其中,直接从 p.mcache 获取空间不需要加锁(单协程),mheap 为全局变量通过 mheap.mcentral 获取空间需要加锁,从 os 分配空间需要系统调用 mmap。此外,堆上分配还需要考虑 gc 导致的 stw 等的影响,因此建议所需空间不是特别大时还是在栈上进行空间的分配。

4.2 Zero GC Zero GC 能够避免 gc 带来的扫描、STW 等,具有一定的性能的收益。

当前 zero gc 的处理,主要包含2种:

无 gc,通过 mmap 或者 cgo.malloc 分配空间,绕过 Go 的内存分配机制 避免或者减少 gc,通过 []byte 等避免因为指针导致的扫描、stw。bigCache 的实现即为此。 在之前的一些开发中,我们使用了大量的基于 0 gc 的库,比如 fastcache 等。也对一些常用函数和机制,如 strings.split 也进行了 0 gc 的优化,其实现如下:

type StringSplitter struct { Idx [8]int // 存储splitter对应的位置信息 src string cnt int }

// Split 分割 func (s *StringSplitter) Split(str string, sep byte) bool { s.src = str for i := 0; i < len(str); i++ { if str[i] == sep { s.Idx[s.cnt] = i s.cnt++

// 超过Idx数据长度则返回空 if int(s.cnt) >= len(s.Idx) { return false } } }

return true }

// At 获得第i个节点数据 func (s *StringSplitter) At(idx int) string { // 没有分割,则返回全量数据 if s.cnt == 0 { return s.src }

if idx == 0 { return s.src[0:s.Idx[idx]] }

cnt := s.cnt

if idx >= cnt { return s.src[s.Idx[cnt-1]+1:] }

return s.src[s.Idx[idx-1]+1 : s.Idx[idx]] } 与常规 strings.split 对比如下,其性能有近4倍左右提升。

➜ test go test --bench='Split' -run=none -benchmem goos: darwin goarch: amd64 pkg: gotest666/test cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz BenchmarkQSplitRaw-12 13455728 76.43 ns/op 64 B/op 1 allocs/op BenchmarkQSplit-12 59633916 20.08 ns/op 0 B/op 0 allocs/op PASS 4.3 GC 的优化 gc 优化相关,主要涉及 GOGC、GOMEMLIMIT。可以通过调整 GOMEMLIMIT 和 GOGC,降低 GC 频率。参见:GOMEMLIMIT。https://weaviate.io/blog/gomemlimit-a-game-changer-for-high-memory-applications

需要注意,此机制只在1.20以上版本生效。 4.4 逃逸 对于一些比较复杂操作,Go 在编译器会在编译期间将相关变量逃逸至堆上。目前可能导致逃逸的机制包含:

函数返回了指针; 栈空间超过了 os 的限制8M; 闭包; 动态类型,如 interface 函数。 目前逃逸分析,可采用 -gcflags="-m -l" 进行查看,如下:

type test1 struct { a int32 b int c int32 }

type test2 struct { a int32 c int32 b int }

func getData() *int { a := 10 return &a }

func main() { fmt.Println(unsafe.Sizeof(test1{})) fmt.Println(unsafe.Sizeof(test2{})) getData() } ➜ gotest666 go build -gcflags="-m -l" main.go

推荐阅读