Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's a function I've used to estimate the memory cost of a managed type. It presumes that objects are allocated sequentially in memory (and not from the large-object heap) so it will not give an accurate result for objects that allocate huge arrays for example. It also does not absolutely guarantee that GC won't corrupt the answer but it makes that very unlikely. </p> <pre><code>/// &lt;summary&gt; /// Gets the memory cost of a reference type. /// &lt;/summary&gt; /// &lt;param name="type"&gt;The type for which to get the cost. It must have a /// public parameterless constructor.&lt;/param&gt; /// &lt;returns&gt;The number of bytes occupied by a default-constructed /// instance of the reference type, including any sub-objects it creates /// during construction. Returns -1 if the type does not have a public /// parameterless constructor.&lt;/returns&gt; public static int MemoryCost(Type type) { // Make garbage collection very unlikely during the execution of this function GC.Collect(); GC.WaitForPendingFinalizers(); // Get the constructor and invoke it once to run JIT and any initialization code ConstructorInfo constr = type.GetConstructor(Type.EmptyTypes); if (constr == null) return -1; object inst1 = constr.Invoke(null); // int size; unsafe { // Create marker arrays and an instance of the type int[] a1 = new int[1]; int[] a2 = new int[1]; object inst2 = constr.Invoke(null); int[] a3 = new int[1]; // Compute the size by determining how much was allocated in between // the marker arrays. fixed (int* p1 = a1) { fixed (int* p2 = a2) { fixed (int* p3 = a3) { size = (int)(((long)p3 - (long)p2) - ((long)p2 - (long)p1)); } } } } return size; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload