Skip to content

Instantly share code, notes, and snippets.

@eaigner
Created August 18, 2013 11:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eaigner/6261179 to your computer and use it in GitHub Desktop.
Save eaigner/6261179 to your computer and use it in GitHub Desktop.
In-memory object tree size
package tree
import (
"reflect"
"unsafe"
)
// Cost calculates the memory size of an object tree.
func Cost(v interface{}) uint64 {
return cost(reflect.ValueOf(v))
}
func cost(v reflect.Value) uint64 {
size := uint64(unsafe.Sizeof(v.Interface()))
switch v.Kind() {
case reflect.Array, reflect.Slice, reflect.String:
for i := 0; i < v.Len(); i++ {
size += cost(v.Index(i))
}
case reflect.Map:
for _, key := range v.MapKeys() {
size += cost(v.MapIndex(key))
}
case reflect.Ptr:
size += cost(v.Elem())
case reflect.Struct:
for i := 0; i < v.NumField(); i++ {
size += cost(v.Field(i))
}
}
return size
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment