Skip to content

Instantly share code, notes, and snippets.

@siennathesane
Created November 14, 2017 16:21
Show Gist options
  • Save siennathesane/357c2e2c7c9aca8b1960dc5e44fc5ed4 to your computer and use it in GitHub Desktop.
Save siennathesane/357c2e2c7c9aca8b1960dc5e44fc5ed4 to your computer and use it in GitHub Desktop.
Compute the size of a map in Golang.
// We're going to compute the actual size of the map, it's total memory footprint.
// In retrospect, we only need the keySize, but I like it, so I'll leave it.
func computeSize(theMap map[string]interface{}) (int, int, int) {
mapLen := uintptr(len(theMap))
baseSize := unsafe.Sizeof(hmapRef{}) + (mapLen * 8)
keySize := mapLen * 8 * unsafe.Sizeof(randKey(theMap))
valSize := mapLen * 8 * unsafe.Sizeof(theMap[randKey(theMap)])
totalSize := baseSize + keySize + valSize
return int(keySize), int(valSize), int(totalSize)
}
func randKey(items map[string]interface{}) string {
for k := range items {
return k
}
return ""
}
//go:linkname hmapRef runtime.hmap
type hmapRef struct{}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment