Skip to content

Instantly share code, notes, and snippets.

@mehradsadeghi
Created December 9, 2024 11:10
Show Gist options
  • Save mehradsadeghi/13da400743a5a60cfb5df354ccdbd830 to your computer and use it in GitHub Desktop.
Save mehradsadeghi/13da400743a5a60cfb5df354ccdbd830 to your computer and use it in GitHub Desktop.
Estimate Map Size in Go
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