Calculating Memory Usage of C# Objects
This article explains how to estimate the memory used by objects in C#, such as Hashtables, SortedLists, and Lists. Precise measurement is difficult, but we can obtain a close approximation.
Approximating Memory Size
The following method offers a reasonable estimate of an object's memory footprint:
<code class="language-csharp">long size = 0; object o = new object(); using (var s = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(s, o); size = s.Length; }</code>
This code serializes the object to a byte stream using BinaryFormatter
. The stream's length serves as a proxy for the object's memory size. Serialization captures the object's data and structure, closely mirroring its in-memory representation.
The above is the detailed content of How Can I Measure the Memory Consumption of Objects in C#?. For more information, please follow other related articles on the PHP Chinese website!