Skip to content

Instantly share code, notes, and snippets.

@karljj1
Last active March 4, 2022 14:39
Show Gist options
  • Select an option

  • Save karljj1/7a3438afe7ab3b3c6f6a18b72aed053e to your computer and use it in GitHub Desktop.

Select an option

Save karljj1/7a3438afe7ab3b3c6f6a18b72aed053e to your computer and use it in GitHub Desktop.
sizeof - Estimate the size of a managed instance
public static int GetSizeOfObject(object obj, StringBuilder sb = null, int indent = 0, bool details = true)
{
if (sb == null)
{
sb = new StringBuilder();
sb.AppendLine("|Name |Type |Size(b)|");
sb.AppendLine("|--- |--- |--- |");
}
if (indent == 0)
sb.AppendLine($"**{obj.GetType().Name}**");
int pointerSize = IntPtr.Size;
int size = 0;
Type type = obj.GetType();
var info = type.GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
foreach (var field in info)
{
if (field.FieldType.IsValueType)
{
if (field.FieldType.IsPrimitive)
{
var sz = Marshal.SizeOf(field.FieldType);
sb.AppendLine($"|{new string('+', indent)}{field.Name}|{field.FieldType}|{sz}|");
size += sz;
}
else
{
var sb2 = new StringBuilder();
var sz = GetSizeOfObject(field.GetValue(obj), avgStringSize, sb2, indent + 1);
sb.AppendLine($"|{new string('+', indent)}**{field.FieldType.Name}**|{field.FieldType}|{sz}|");
if (details)
sb.Append(sb2.ToString());
size += sz;
}
}
else
{
size += pointerSize;
sb.AppendLine($"|{new string('+', indent)}{field.Name} Reference|{field.FieldType}|{pointerSize}|");
}
}
if (indent == 0)
{
sb.AppendLine($"\nTotal Size: {size}");
Debug.Log(sb.ToString());
}
return size;
}
@karljj1

karljj1 commented Mar 4, 2022

Copy link
Copy Markdown
Author

A quick and dirty way to try and see how much memory an instance is using. Prints a markdown dump of the breakdown.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment