Home > Backend Development > C++ > How Can I Measure the Memory Consumption of Objects in C#?

How Can I Measure the Memory Consumption of Objects in C#?

DDD
Release: 2025-01-14 17:02:47
Original
742 people have browsed it

How Can I Measure the Memory Consumption of Objects in C#?

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template