19 using System.Collections.Generic;
21 namespace Lucene.Net.Util
40 private IDictionary<object, object> seen;
43 private int arraySize;
44 private int classSize;
46 private bool checkInterned;
79 this.memoryModel = memoryModel;
80 this.checkInterned = checkInterned;
83 seen =
new IdentityDictionary<object, object>(64);
89 public long EstimateRamUsage(System.Object obj)
91 long size = Size(obj);
96 private long Size(System.Object obj)
103 if (checkInterned && obj is System.String && obj == (System.Object) String.Intern(((System.String) obj)))
112 if (seen.ContainsKey(obj))
120 System.Type clazz = obj.GetType();
123 return SizeOfArray(obj);
129 while (clazz != null)
131 System.Reflection.FieldInfo[] fields = clazz.GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Static);
132 for (
int i = 0; i < fields.Length; i++)
134 if (fields[i].IsStatic)
139 if (fields[i].FieldType.IsPrimitive)
141 size += memoryModel.GetPrimitiveSize(fields[i].FieldType);
149 System.Object value_Renamed = fields[i].GetValue(obj);
150 if (value_Renamed != null)
152 size += Size(value_Renamed);
155 catch (System.UnauthorizedAccessException)
161 clazz = clazz.BaseType;
167 private long SizeOfArray(System.Object obj)
169 int len = ((System.Array) obj).Length;
174 long size = arraySize;
175 System.Type arrayElementClazz = obj.GetType().GetElementType();
176 if (arrayElementClazz.IsPrimitive)
178 size += len * memoryModel.GetPrimitiveSize(arrayElementClazz);
182 for (
int i = 0; i < len; i++)
184 size += refSize + Size(((System.Array) obj).GetValue(i));
191 private const long ONE_KB = 1024;
192 private static readonly
long ONE_MB = ONE_KB * ONE_KB;
193 private static readonly
long ONE_GB = ONE_KB * ONE_MB;
196 public static System.String HumanReadableUnits(
long bytes, System.IFormatProvider df)
198 System.String newSizeAndUnits;
200 if (bytes / ONE_GB > 0)
202 newSizeAndUnits = System.Convert.ToString(((
float) bytes / ONE_GB), df) +
" GB";
204 else if (bytes / ONE_MB > 0)
206 newSizeAndUnits = System.Convert.ToString((
float) bytes / ONE_MB, df) +
" MB";
208 else if (bytes / ONE_KB > 0)
210 newSizeAndUnits = System.Convert.ToString((
float) bytes / ONE_KB, df) +
" KB";
214 newSizeAndUnits = System.Convert.ToString(bytes) +
" bytes";
217 return newSizeAndUnits;