Approximating Memory Usage of C# Objects
Precisely determining the memory footprint of a C# object is difficult. However, a reliable estimate can be obtained using serialization.
Estimating Object Size using Serialization
This method involves serializing the object to a stream and then checking the stream's length. While not perfectly accurate, it offers a reasonable approximation of the object's memory consumption.
<code class="language-csharp">long size = 0; object o = new object(); using (Stream s = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(s, o); size = s.Length; }</code>
Illustrative Example
This technique can be applied to various collection types, such as Hashtable
, SortedList
, and List<string>
, to get an idea of their memory usage.
Important Consideration: This approach may not be suitable for all situations demanding precise memory measurements. For more accurate results, dedicated memory profiling tools are recommended.
The above is the detailed content of How Can I Estimate the Memory Size of a C# Object?. For more information, please follow other related articles on the PHP Chinese website!