-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEstimations.cs
104 lines (90 loc) · 3.13 KB
/
Estimations.cs
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
using System.Reflection;
using System.Runtime.Caching;
using System.Runtime.InteropServices;
namespace NTDLS.FastMemoryCache
{
/// <summary>
/// Various static functions for determining the size of .net objects.
/// </summary>
static public class Estimations
{
private static readonly MemoryCache _reflectionCache = new("Estimations:_reflectionCache");
private static readonly CacheItemPolicy _slidingOneMinute = new()
{
SlidingExpiration = TimeSpan.FromSeconds(60)
};
/// <summary>
/// Estimates the amount of memory that would be consumed by a class instance.
/// </summary>
static public int ObjectSize(object? obj)
{
if (obj == null)
{
return 0;
}
int totalSize = 0;
var type = obj.GetType();
var fieldsAndProperties = (FieldInfo[])_reflectionCache.Get(type.Name);
if (fieldsAndProperties == null)
{
fieldsAndProperties = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
_reflectionCache.Add(type.Name, fieldsAndProperties, _slidingOneMinute);
}
foreach (var field in fieldsAndProperties)
{
var fieldType = field.FieldType;
var fieldValue = field.GetValue(obj);
totalSize += ObjectFieldSize(fieldType, fieldValue);
}
return totalSize;
}
/// <summary>
/// Estimates the amount of memory that would be consumed by a field in a class instance.
/// </summary>
static public int ObjectFieldSize(Type? type, object? obj)
{
if (type == null || obj == null)
{
return 0;
}
if (type.IsValueType)
{
if (type.IsEnum)
{
return sizeof(int);
}
else if (type.IsGenericType)
{
return ObjectSize(obj);
}
else
{
return Marshal.SizeOf(type);
}
}
else if (type == typeof(string))
{
var stringValue = obj as string;
return (stringValue?.Length ?? 0) * sizeof(char);
}
else if (type.IsArray)
{
int totalSize = 0;
if (obj is Array array)
{
for (int i = 0; i < array.Length; i++)
{
var arrayValue = array.GetValue(i);
var arrayElementType = arrayValue?.GetType();
totalSize += ObjectFieldSize(arrayElementType, arrayValue);
}
}
return totalSize;
}
else
{
return ObjectSize(obj);
}
}
}
}