Jeffrey Cameron
Jeffrey Cameron

Reputation: 10285

How to measure the amount of memory an individual object takes in .NET

I'm wondering if there is a simple command or instruction in C#/.NET and/or Visual Studio that can tell me how much memory an individual object is taking up? I have a sneaking suspicion that the sizeof() operator is going to lie to me ... am I justified in this belief?

There is a somewhat related question here, but no definitive answer is given on how to measure an individual object

Upvotes: 9

Views: 5112

Answers (4)

serhio
serhio

Reputation: 28586

If you can - Serialize it!

Dim myObjectSize As Long

Dim ms As New IO.MemoryStream
Dim bf As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
bf.Serialize(ms, myObject)
myObjectSize = ms.Position

Upvotes: 3

John Alexiou
John Alexiou

Reputation: 29244

I wonder how System.Runtime.InteropServices.Marshal.SizeOf() works? There are a lot of interesting static functions under the Marshal object that might be helpful here.

Upvotes: 1

Mikael Svenson
Mikael Svenson

Reputation: 39697

There's no easy way and sizeof will only be good for value types. A typical object contains references to lists and other objects, so you would need to traverse all pointers in order to get the actual byte count, and add the pointer sizes as well.

You can check out the .Net Profiling API, or use a memory profiler like dotTrace. A memory profiler will at least help you to see where memory is allocated and if memory allocation is an issue in your application. This is often more useful than the actual object size.

Upvotes: 3

Kelsey
Kelsey

Reputation: 47726

There is no definitive way because it's not simple for just any type of object.

What if that object contains references to other objects? What if those other objects have other objects referencing them? Which object actually owns that memory space? Is it the one that created it or the last one to touch it? At any one point it could have different owners. Or do you just care about how much space the reference takes?

There is also a ton of questions that have asked this as well... a quick search turns up:

How to get object size in memory?

C#: Memory usage of an object

Find out the size of a .net object

How much memory does a C#/.NET object use?

and the list goes on an on...

Upvotes: 8

Related Questions