Welcome to MSDN Blogs Sign in | Join | Help

Mark Brown's Blog

Interesting facts about BizTalk, SharePoint, .Net, and more ...
How to determine size of .NET managed object in memory (like a sizeof for reference types)

An approximate way to determine the size of object usage in memory can be done by checking the total memory before and after the creation of the object.  In the following example it is assumed you have a class named foo.

long StopBytes = 0;
foo myFoo;

long StartBytes = System.GC.GetTotalMemory(true);
myFoo = new foo();
StopBytes = System.GC.GetTotalMemory(true);
GC.KeepAlive(myFoo); // This ensure a reference to object keeps object in memory

MessageBox.Show("Size is " + ((long)(StopBytes - StartBytes)).ToString());

Anyone have better suggestions?

P.S. As one of the people that commentted, this is not thread-safe and should not be used in a production environment as how the CLR allocates memory can vary.  Keep those comments coming ...

Posted: Monday, April 24, 2006 10:18 PM by mab

Comments

ernow said:

I like this solution but it isn't very threadsafe...

When another thread allocates (or worse causes the release of) memory your calculation might go wrong and give you the impression that the object has a negative size... (now that would be cool if it was true!)

Read this to get more info: http://blogs.msdn.com/cbrumme/archive/2003/04/15/51326.aspx

Cheers

Erno
# April 25, 2006 2:36 AM

Jason Haley said:

# April 25, 2006 7:07 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker