用pprof分析map和slice的内存调用

Golang
344
0
0
2022-09-04

学习了go的map和slice的内存结构,可以从理论上得知存储同等数量相同元素,map占用的内存比slice大,那么怎么去验证这一点呢,下面我用pprof实际验证一下。

假设元素类型定义如下:

type canceler struct {
code int
data uintptr
}

先测试slice的内存占用,代码如下:

func sliceMemoryUse(num int) {
max := make([]canceler, num, num)
_ = &max
}
func main() {
num := 1024 * 1024
sliceMemoryUse(num)
f, _ := os.Create("mem.out")
pprof.WriteHeapProfile(f)
f.Close()
}
/*
这里用到了runtime.pprof包来收集内存信息,如果要收集cpu的信息,则使用如下代码:
f, err := os.Create("cpu.out")
pprof.StartCPUProfile(f)
// do some stuff
pprof.StopCPUProfile()
*/

使用pprof检查一下

go tool pprof --alloc_space mem.out
flat flat% sum% cum cum%
16MB 100% 100% 16MB 100% main.sliceMemoryUse (inline)
0 0% 100% 16MB 100% main.main
0 0% 100% 16MB 100% runtime.main

再测试map的内存占用,代码如下:

func mapMemoryUse(num int) {
max := make(map[canceler]struct{}, num)
_ = &max
}
func main() {
num := 1024 * 1024
mapMemoryUse(num)
f, _ := os.Create("mem.out")
pprof.WriteHeapProfile(f)
f.Close()
}

使用pprof检查一下

go tool pprof --alloc_space mem.out
flat flat% sum% cum cum%
38.25MB 100% 100% 38.25MB 100% main.mapMemoryUse (inline)
0 0% 100% 38.25MB 100% main.main
0 0% 100% 38.25MB 100% runtime.main