Nick Bauer
Nick Bauer

Reputation: 1072

.net - Signal to the Garbage Collector than an object is ready for removal?

I was reading up on the performance of the .Net garbage collector, and I'm building a set of inter-referencing classes for my data model. I have implemented Delete() methods to dereference the object from all connected objects, ensuring that the object will be collectable.

While I do not currently know if this will be an issue for my application, I got to thinking about what would happen to objects that are promoted to later generations and then deleted. It is possible then that they would remain in memory for a long time.

Is it possible to tell the Garbage Collector that a particular object should be 'demoted' and freed during the next Gen0 collection?

Upvotes: 0

Views: 261

Answers (2)

Slugart
Slugart

Reputation: 4680

One of the optimisations possible with a garbage collector is to leave objects unreferenced objects in memory for as long as possible thus deferring collection until it is absolutely necessary. This can yield fewer collections and will mutualise the cost of the collection across more objects/memory.

Is it really a problem if your objects remain in memory for a long time after being dereferenced? If your machine has enough free memory and your application's footprint after dereferencing is not growing is there really a downside?

The collection cost is a guaranteed cost whereas the cost of using extra memory is not certain - it may or may not impact your program/other programs. The key point of this optimisation is that we give up a certain cost in exchange for an uncertain one.

Upvotes: 1

Sam Harwell
Sam Harwell

Reputation: 99869

Aside from removing references to your object calling GC.Collect, you cannot manually interact with the GC.

Regarding this quote:

While I do not currently know if this will be an issue for my application, I got to thinking about...

When it comes to GC in a managed language, until it's a problem, stop thinking about it. If you don't have a detailed understanding of the particular algorithms in use in the particular GC for your particular runtime, then you are more likely to hurt the performance of your application than help it by trying to modify the default behavior of the GC.

Upvotes: 1

Related Questions