How to get memory size of variable in Go?

后端 未结 3 1916
南方客
南方客 2020-11-27 07:17

I am curious about the memory cost of map and slice, so I wrote a program to compare the sizes. I get the memory size by unsafe.Sizeof(s)

3条回答
  •  暖寄归人
    2020-11-27 07:52

    This incurs some marshaling overhead but I've found it's the simplest way during runtime to get the size of a value in go. For my needs the marshaling overhead wasn't a big issue so I went this route.

    func getRealSizeOf(v interface{}) (int, error) {
        b := new(bytes.Buffer)
        if err := gob.NewEncoder(b).Encode(v); err != nil {
            return 0, err
        }
        return b.Len(), nil
    }
    

提交回复
热议问题