-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmem.go
41 lines (39 loc) · 1011 Bytes
/
mem.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package mem
import (
"reflect"
)
func GetMemoryConsumption(variable interface{}, isRecursed ...bool) int {
var getValue bool
if len(isRecursed) > 0 {
getValue = isRecursed[0]
}
totalSize := 0
var value reflect.Value
if getValue {
value = variable.(reflect.Value)
} else {
if reflect.ValueOf(variable).Kind() == reflect.Ptr {
value = reflect.ValueOf(variable).Elem()
} else {
value = reflect.ValueOf(variable)
}
}
if value.Kind() == reflect.Map {
iter := value.MapRange()
for iter.Next() {
totalSize += GetMemoryConsumption(iter.Key(), true)
totalSize += GetMemoryConsumption(iter.Value(), true)
}
} else if value.Kind() == reflect.Slice {
for i := 0; i < value.Len(); i++ {
totalSize += GetMemoryConsumption(value.Index(i), true)
}
} else if value.Kind() == reflect.Struct {
for i := 1; i < value.NumField(); i++ {
totalSize += GetMemoryConsumption(value.Field(i), true)
}
} else {
totalSize += int(reflect.TypeOf(value).Size())
}
return totalSize
}