Computing the memory footprint (or byte length) of a map

后端 未结 1 398
悲哀的现实
悲哀的现实 2020-12-16 05:18

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\"

相关标签:
1条回答
  • 2020-12-16 06:02

    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 is a constant defined as:

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

    Where theMap is your map value, x is a value of the map's key type and y a value of the map's value type.

    You'll have to share the hmap structure with your package via assembly, analogously to thunk.s in the runtime.

    0 讨论(0)
提交回复
热议问题