栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

计算映射的内存占用量(或字节长度)

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

计算映射的内存占用量(或字节长度)

这是地图标题的定义:

// A header for a Go map.type hmap struct {    // Note: the format of the Hmap is enpred in ../../cmd/gc/reflect.c and    // ../reflect/type.go.  Don't change this structure without also changing that pre!    count int // # live cells == size of map.  Must be first (used by len() builtin)    flags uint32    hash0 uint32 // hash seed    B     uint8  // log_2 of # of buckets (can hold up to loadFactor * 2^B items)    buckets    unsafe.Pointer // array of 2^B Buckets. may be nil if count==0.    oldbuckets unsafe.Pointer // previous bucket array of half the size, non-nil only when growing    nevacuate  uintptr        // progress counter for evacuation (buckets less than this have been evacuated)}

计算其大小非常简单(unsafe.Sizeof)。

这是地图指向的每个单独存储区的定义:

// A bucket for a Go map.type bmap struct {    tophash [bucketCnt]uint8    // Followed by bucketCnt keys and then bucketCnt values.    // NOTE: packing all the keys together and then all the values together makes the    // pre a bit more complicated than alternating key/value/key/value/... but it allows    // us to eliminate padding which would be needed for, e.g., map[int64]int8.    // Followed by an overflow pointer.}

bucketCnt
是一个常量,定义为:

bucketCnt     = 1 << bucketCntBits // equals decimal 8bucketCntBits = 3

最终计算将为:

unsafe.Sizeof(hmap) + (len(theMap) * 8) + (len(theMap) * 8 * unsafe.Sizeof(x)) + (len(theMap) * 8 * unsafe.Sizeof(y))

theMap
地图值在哪里,
x
是地图键类型
y
的值和地图值类型的值。

hmap
thunk.s
运行时类似,您必须通过组装与包共享结构。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/471108.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号