Home > Backend Development > C++ > How Can I Estimate the Memory Size of a C# Object?

How Can I Estimate the Memory Size of a C# Object?

Barbara Streisand
Release: 2025-01-14 17:07:48
Original
138 people have browsed it

How Can I Estimate the Memory Size of a C# Object?

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template