Waldo Bronchart
Waldo Bronchart

Reputation: 10532

.NET garbage profiling: calculate how much garbage a piece of code is making

I would like to write a utility class that will help me determine how much garbage a certain piece of code is making.

Something I can use like this: GarbageProfiler.Start(); and int numGarbage = GarbageProfiler.End();

Idea is simple enough. But does it make sense to do so? Are there any tools out there to do just this?

Upvotes: 5

Views: 225

Answers (3)

Henk Holterman
Henk Holterman

Reputation: 273244

But does it make sense to do so?

No.

You would at least have to differentiate between the Generations of the garbage.

The memory that a certain piece of code allocates and still holds at the end is (can be) much more expensive than the objects it quickly released.

Upvotes: 1

Emond
Emond

Reputation: 50672

The amount of garbage that is behind a reference will change from run to run depending on whether the reference holds that last reference(s) to the objects or not. So predicting the amount of garbage is very hard.

There are also quite some performance counters that you can read just before a GC.Collect() and after it that could give you an idea.

I do question the use of this all; you will never know when the GC kicks in so you do not know when the garbage will be recycled. And calling GC.Collect() is not a very good idea (most of the time)

Upvotes: 0

Tedd Hansen
Tedd Hansen

Reputation: 12314

There are quite a few memory profilers already out there. A quick search on Google will give you several.

There is even an API for memory profiling .Net applications.

Upvotes: 0

Related Questions