What are some ways to get the size of an object in memory? It is possible not necessarily in (code).

  • one
    And what is the size of the object? If, for example, an object contains references to other objects, are those objects considered? - VladD
  • @VladD Good question. Rather consider than not. I thought more about collections. - RusArt
  • @ RuslanArtamonov, the WinDBG method will show you the full size of the object, i.e. its size + the sum of the sizes of all internal objects. The BinaryFormatter method will also show the total size. In extreme cases, in WinDBG you can see the size of the related objects separately. - Anton Komyshan

3 answers 3

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)).

  1. We start WinDbg as administrator, preferably.
  2. Attach to our process.
  3. Download psscor4: .load C:\Symbols\Psscor4\x86\x86\psscor4.dll - here you need to substitute your own path.
  4. Looking for your object. There are several ways, for example, the easiest for simple memory tests is to execute the command !DumpHeap and you will see for example this: result! DumpHeap

  5. Then we execute the command !DumpHeap /d -mt 00414da0 , where 00414da0 is the address of your object. And we see: enter image description here

  6. 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 , where 0df73294 is the address of the object. And we see: enter image description here

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; } } 
    1. Record in the memory of the stream and measure it.
    2. Using hellish khaki pointers to get to CLR-type meta information
    3. sizeof () for standard types and user structures without references to reference types (otherwise the pointer size will be returned).
    4. 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