Created
November 14, 2017 16:21
-
-
Save siennathesane/357c2e2c7c9aca8b1960dc5e44fc5ed4 to your computer and use it in GitHub Desktop.
Compute the size of a map in Golang.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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