Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 707
zaq Avatar asked May 02 '12 00:05

zaq


People also ask

What is Gc collect in C#?

It performs a blocking garbage collection of all generations. All objects, regardless of how long they have been in memory, are considered for collection; however, objects that are referenced in managed code are not collected. Use this method to force the system to try to reclaim the maximum amount of available memory.

What is Gc time spent?

Displays the percentage of elapsed time that was spent performing a garbage collection since the last garbage collection cycle. This counter usually indicates the work done by the garbage collector to collect and compact memory on behalf of the application.

What is performance counter in C#?

Performance counters enable us to publish, capture, and analyze the performance data of running code. A performance graph is a two-dimensional plot with one axis indicating time elapsed and the other reporting relevant relative or actual performance statistics.


1 Answers

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.

like image 57
svick Avatar answered Sep 19 '22 11:09

svick