zaq
zaq

Reputation: 2661

GC.Collect() and PerformanceCounter

A colleague of mine is convinced there is a memory leak in Oracle's odp.net ado.net implementation. He has written a test program to test this theory and is doing the following after calling dispose on each object in order to determine how much memory is being freed:

PerformanceCounter p = new PerformanceCounter("Memory", "Available Bytes");

GC.Collect();
GC.WaitForPendingFinalizers();

float mem = p.NextValue();

The resulting performance value is then compared with a value retrieved prior to disposing of the object. Will this produce accurate results?

Upvotes: 9

Views: 886

Answers (1)

svick
svick

Reputation: 244767

I think the best way to do this is to use GC.GetTotalMemory(true). You can call it before allocating the object to record how much memory was allocated then. Then you create your object, maybe perform some operation on it, dispose it, make sure there are no references to it (probably just setting the local variable to null) and then call it again.

Keep in might that the returned value might not be completely exact, per the documentation, the method will return:

A number that is the best available approximation of the number of bytes currently allocated in managed memory.

After that, you can compare the two values. If you do this repeatedly, you can see whether the object is actually leaking managed memory.

Of course, this won't help you if the object leaks unmanaged memory.

Another option is to use a memory profiler, but that might be an overkill if you know where exactly the memory might leak.

Upvotes: 2

Related Questions