【问题标题】:Computing the memory footprint (or byte length) of a map计算映射的内存占用(或字节长度)
【发布时间】:2015-10-29 02:48:28
【问题描述】:

我想将地图限制为最大 X 字节。不过,似乎没有直接的方法来计算地图的字节长度。

"encoding/binary" 包有一个不错的Size function,但它只适用于切片或“固定值”,不适用于地图。

我可以尝试从映射中获取所有键/值对,推断它们的类型(如果它是 map[string]interface{})并计算长度 - 但这既麻烦又可能不正确(因为这会排除“内部" 地图本身的成本 - 管理指向元素的指针等)。

有什么建议的方法吗?最好是代码示例。

【问题讨论】:

  • 你不能以可靠的方式做你想做的事:例如。 “内部 golang 成本”取决于您机器的字长。我虽然认为“地图使用 X 字节”的概念是有缺陷的;考虑一个包含切片的地图:您是否将支持数组的字节数计入地图?我建议搜索一个不同的解决方案,特别是因为使用 interface{} 有难闻的气味。
  • 感谢您的评论。用例实际上相当简单:我想对缓存施加大小限制(而不是时间限制)。如果我想使用映射(可以说是在 Go 中用作缓存对象的最合适的原语)(甚至假设它不是字符串/接口的映射)我在语言中的选择是什么(使用外部这个工具似乎有点矫枉过正)?
  • 限制缓存中的数据量是一个有效的用例,但这只有在缓存中存储大量可变大小的数据时才有意义,这意味着地图本身的开销将是微不足道。如果你有固定大小的数据,你可以通过地图的 len 来限制。

标签: dictionary go


【解决方案1】:

这是 the definition 的地图标题:

// A header for a Go map.
type hmap struct {
    // Note: the format of the Hmap is encoded in ../../cmd/gc/reflect.c and
    // ../reflect/type.go.  Don't change this structure without also changing that code!
    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
    // code 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 8
bucketCntBits = 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

【讨论】:

  • JFYI thunk.s 已替换为 //go:linkname compiler directive
  • 你能更新这个答案吗?显然,这些都不再起作用了。 hmap 结构完全不同,您的答案不考虑容量,您不能通过程序集共享结构(也不能通过 go:linkname)
  • Smaug:您好,事实上,map 的实现在未来会不断变化。因此,我将答案作为指导而不是解决方案。您仍然可以使用程序集来共享名称。
  • @thwd 完整的 sn-p 会有所帮助,而不是部分响应,然后我们必须在其他地方寻找如何使用程序集来共享名称,您为什么不提出一个独立的响应呢? ?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-31
  • 1970-01-01
  • 2014-09-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多