For the past few days I've been tracking down some nasty memory leaks in our product and SciTech's MemProfiler has saved my bacon. It turns out that we had a number of short lived objects (foo) subscribing to events on long lived objects (bar) and never releasing those events. As a result the objects the foo objects lasted forever.
The documentation is a bit weak so for the benefit of first time users, here is how I use it:
- Start your application and do "some work"
- Take a snapshot
- Do some more work and take another snapshot
- Now the fun begins: Go to the classes tab (left most)
- Sort by the delta either on number of instances or bytes and look for unexpected growth
- Double Click on a suspicious class (MemProfiler switches to the class details tab)
- Double Click on an interesting instance (MemProfiler switches to the instance tab)
- Laid out in front of you are:
list of Objects that reference you
paths back to the root for each instance
the allocation stack for this object
- Find the reference to your object that is keeping it alive and fix the code
- Rerun the process to verify
- Jump for joy that this problem was so damn simple to fix
Now I just have to figure out how to write unit tests that will detect these leaks. Nothing's perfect and I have few feature requests for SciTech:
- Given an instance I would like to be able to display a graph of what it references and what references it. Often the references we've stumbled across are loops and so shouldn't stop the objects from being garbage collected.
- In the Classes tab, I would like a field that gives the total number of bytes for this object and all its dependants. MemProfiler tells me our application has allocated a large number of int32's. By itself that's not very useful - knowing what data structures they belong to is.
- Work NUnit/MbUnit without crashing - the current version has some problems with reflection. Andreas has promised the next version will fix this.
- More information for 'undisposed instances' (IDisposeable objects that weren't disposed before they went out of scope). Specifically where these objects allocated. Otherwise its like tracking down a needle in haystack. We allocate over 200 Bitmaps - most of which we handle well. It was a pain to find the few that SciTech said were leaking.
- Better documentation
Best part it only costs $100 US.