Files
mapsize/mapsize.go
Lucien Coffe 0e5dd520cb init
2023-05-26 09:43:36 +02:00

36 lines
756 B
Go

package mapsize
import (
"math"
"unsafe"
)
type Mapsize struct {
ptrSize uint64
intSize uint64
dataSize uint64
len uint64
}
func New() *Mapsize {
return &Mapsize{
ptrSize: uint64(unsafe.Sizeof(&[]int{0}[0])),
intSize: uint64(unsafe.Sizeof(int(0))),
}
}
func (m *Mapsize) Add(k, v int) {
m.len++
// string: ptr=psize, cap=isize, len=isize
m.dataSize += uint64(k) + uint64(v) + 4*m.intSize + 2*m.ptrSize
}
func (m *Mapsize) Size() uint64 {
hmapSize := m.intSize + 1 + 1 + 2 + 4 + m.ptrSize*4
buckets := uint64(1 << uint(math.Ceil(math.Log2(float64(m.len)))))
// entry overhead = key ptr, value ptr, hash, next
// bucket overhead = 2 ptr (overflow)
return hmapSize + m.dataSize + m.len*(4*m.ptrSize) + buckets*(2*m.ptrSize)
}