gpt4 book ai didi

go - 在 golang 中声明一个空的 map[string]interface{} 的内存成本/开销是多少?

转载 作者:数据小太阳 更新时间:2023-10-29 03:31:19 30 4
gpt4 key购买 nike

<分区>

出于好奇,来自source code

type hmap struct {
count int // 1 word
flags uint8
B uint8
noverflow uint16
hash0 uint32 // = 8 byte

buckets unsafe.Pointer // 1 word
oldbuckets unsafe.Pointer // 1 word
nevacuate uintptr // 1 word

extra *mapextra // 1 word
}

所以它至少是:5 字 + 8 字节

但为什么 creation cost is 0 ? -


package main

import (
"fmt"
"runtime"
)

func main() {
var m1, m2 runtime.MemStats
var i byte

runtime.ReadMemStats(&m1)
mp := map[byte]byte{}
runtime.ReadMemStats(&m2)
fmt.Println("Bytes allocated on creation:", m2.Alloc-m1.Alloc)
for i = 0; i < 100; i++ {
runtime.ReadMemStats(&m1)
mp[i] = i
runtime.ReadMemStats(&m2)
fmt.Printf("Bytes allocated on assignment %d: %d\n", i, m2.Alloc-m1.Alloc)
}
}

Playground :https://play.golang.org/p/iyYshDzexQt

输出:

Bytes allocated on creation: 0

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com