为什么这段代码找不到内存使用(m2-m1)和(m4-m3)?
为什么 (m3-m2) 和 (m5-m4) 需要分配额外的内存?
type T struct {
B uint8
S string
I int
}
func memUsage(mOld, mNew *runtime.MemStats) {
fmt.Println("Alloc:", mNew.Alloc-mOld.Alloc,
"HeapAlloc:", mNew.HeapAlloc-mOld.HeapAlloc,
"TotalAlloc:", mNew.TotalAlloc-mOld.TotalAlloc)
}
func main() {
var m1, m2, m3, m4, m5, m6 runtime.MemStats
runtime.ReadMemStats(&m1)
t := T{}
runtime.ReadMemStats(&m2)
fmt.Println(t)
memUsage(&m1, &m2)
runtime.ReadMemStats(&m3)
t2 := "abc"
runtime.ReadMemStats(&m4)
fmt.Println(t2)
memUsage(&m3, &m4)
runtime.ReadMemStats(&m5)
t3 := map[int]string{1: "x"}
runtime.ReadMemStats(&m6)
fmt.Println(t3)
memUsage(&m5, &m6)
memUsage(&m2, &m3)
memUsage(&m4, &m5)
}
输出
{0 0}
Alloc: 0 HeapAlloc: 0 TotalAlloc: 0
abc
Alloc: 0 HeapAlloc: 0 TotalAlloc: 0
map[1:x]
Alloc: 256 HeapAlloc: 256 TotalAlloc: 256
Alloc: 432 HeapAlloc: 432 TotalAlloc: 432
Alloc: 64 HeapAlloc: 64 TotalAlloc: 64
相关分类