What are some ways to get the size of an object in memory? It is possible not necessarily in (code).
3 answers
You can use WinDBG with psscor4.dll for the .NET platform (there is still Son of Strike but for your task psscor4 is enough (for CLR version 2. * you need to take psscor2)).
- We start WinDbg as administrator, preferably.
- Attach to our process.
- Download psscor4:
.load C:\Symbols\Psscor4\x86\x86\psscor4.dll- here you need to substitute your own path. Looking for your object. There are several ways, for example, the easiest for simple memory tests is to execute the command
!DumpHeapand you will see for example this:
Then we execute the command
!DumpHeap /d -mt 00414da0, where00414da0is the address of your object. And we see:
And the last step (in this simple example) is to execute the command to get the size of an object by its address
!objsize 0df73294, where0df73294is the address of the object. And we see:
My test code:
public static class Program { private static void Main() { MyObject myObject = new MyObject { S = "1234567895555555555555555555555555555555", Type = 0 }; Console.ReadKey(); // не забудьте приаттачится в нужный момент. Console.WriteLine(myObject); } } public class MyObject { public int Type { get; set; } public string S { get; set; } } - Record in the memory of the stream and measure it.
- Using
hellish khakipointers to get to CLR-type meta information - sizeof () for standard types and user structures without references to reference types (otherwise the pointer size will be returned).
- Use a profiler.
The first three methods work in runtime.
- Thank! Here, in the first case, we will not get the size in memory, but how much memory is needed to represent the object in deserialized form, different numbers may turn out. I dig out with the profiler, there somehow I have to intuitively search by the memory snapshot. You can make a mistake with the object, for example, several objects of the same type, which of them is necessary? - RusArt
You can play around with ClrMD , dump the process and go through the heap of Walking Managed Objects in the Process
BinaryFormattermethod will also show the total size. In extreme cases, in WinDBG you can see the size of the related objects separately. - Anton Komyshan