Writing Automated Performance Tests

I recently found out how easy it is to see how much total RAM your .NET app uses: `GC.GetTotalMemory(false)`. This gives you a simple total number of bytes that your app is using.

Throwing this into the trace that outputs the game FPS every second, I noticed a repetitive workflow where my game’s RAM usage kept climbing, from around 10MB (baseline) to over 30MB!

Having a qualified, quantified problem (potentially unlimited growth of memory usage, i.e. a memory leak) I sat out to answer an important question: could I somehow write an automated test that would check if this workflow leaked memory?

The answer was a resounding yes. Using the very powerful Moq framework, I was able to rip out most external dependencies and isolate my workflow to two calls: a constructor and Initialize method on one of my Screen subclasses.

Once I did this, simply creating and disposing 10k objects and checking the memory usage (before and after) indicated whether the usage shot up. A small rise (10k? 100k?) was probably insignificant; in my case, I saw more than a 20MB increase in RAM usage.

Also, one key here is to run GC.GetTotalMemory(true). This forces the GC to collect anything immediately, which is slower, but necessary. Without it, we can’t tell if the memory increase is due to disposed objects that the GC didn’t get around to disposing yet.

The culprit? Appending event handlers in the constructor which should have been removed on subsequent calls to dispose (but weren’t).

The conclusion? Testing for memory leaks is not hard, and can be very useful under certain circumstances, provided you have enough infrastructure in place to mock out dependencies.

About Ashiq Alibhai, PMP

Ashiq has been coding C# since 2005. A desktop, web, and RIA application developer, he's touched ASP.NET MVC, ActiveRecord, Silverlight, NUnit, and all kinds of exciting .NET technologies. He started C# City in order to accelerate his .NET learning.
This entry was posted in Core .NET, Silverlight, Wndows Forms, WPF and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *