Created
December 9, 2024 11:10
-
-
Save mehradsadeghi/13da400743a5a60cfb5df354ccdbd830 to your computer and use it in GitHub Desktop.
Estimate Map Size in Go
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
func estimateMapSize(m map[string]bool) uintptr { | |
var totalSize uintptr | |
ch := make(chan uintptr) | |
wg := sync.WaitGroup{} | |
// Iterate over each key-value pair | |
for key, value := range m { | |
wg.Add(1) | |
go func() { | |
defer wg.Done() | |
// Size of key (string) | |
ch <- uintptr(len(key)) + uintptr(unsafe.Sizeof(key)) | |
// Size of value (int) | |
ch <- uintptr(unsafe.Sizeof(value)) | |
}() | |
} | |
go func() { | |
wg.Wait() | |
close(ch) | |
}() | |
for v := range ch { | |
totalSize += v | |
} | |
// Add estimated overhead for the map's internal structure | |
// This will depend on the map size and implementation; it's a rough estimate | |
// Assume some overhead for buckets and hash table | |
totalSize += uintptr(unsafe.Sizeof(m)) // Size of the map structure itself | |
// This is an approximation, actual internal structure can vary | |
return totalSize | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment