hmap  thunk.s 

I want to limit a map to be maximum X bytes. It seems there is no straightforward way of computing the byte length of a map though.

"encoding/binary"Size
map[string]interface{}

Any suggested way of doing this? preferably a code example.

This is the definition for a map header:

// 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)
}

Calculating its size is pretty straightforward (unsafe.Sizeof).

This is the definition for each individual bucket the map points to:

// 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

The final calculation would be:

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

这篇关于Golang:计算地图的内存占用(或字节长度)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!