How can you explore the managed heap in a .NET application to identify possible memory optimizations?

WinDbg might be a useful tool for you. It comes with the Debugging Tools for Windows.

Once your app is running, you can attach WinDbg and explore the managed heap. (Or you can take a memory dump and explore it offline). It will be able to very quickly tell you the object types consuming the largest amounts of memory.

First you will need to load the SOS extension which enables debugging of managed applications:

.loadby sos mscorwks

Then you can use !dumpheap to get heap information, the -stat switch gives overall heap info on which types are allocated:

!dumpheap -stat

The -type parameter gives specific information on allocated instances of the specified type:

!dumpheap -type System.String

There's a bunch of other commands you might find helpful like:

  • !gcroot - to follow an allocated object back up it's root to find why it is in memory.
  • !dumpobj - to dump out a specific object so you can see it's contents.
  • !EEHeap - to give some general heap stats.

MSDN has a full list of SOS commands and their switches.

WinDbg is a pretty complex tool, but there are lots of tutorials and guides online if you search to help you get started. Alternatively, I can recommend the book Debugging Microsoft .NET 2.0 Applications by John Robbins which goes into some good detail in the .net debugging abilities of WinDbg and SOS.

You can load the SOS extension into visual studio instead by entering this into the immediate window, then you should be able to use the SOS commands directly in the VS immediate window:

.load SOS.dll

You also might find the CLR Profiler and this Usage guide helpful.


The new tool is PerfView which can show reference tree and also do diffing