Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically invoke garbage collector

Is there a way to invoke the garbage collector on a specific object within managed memory from an application?

e.g. (in pseudo-code)

Read myString from file;
perform arbitrary operation on myString;
invoke garbage-collector to remove myString
like image 668
Rich Avatar asked Mar 17 '26 12:03

Rich


2 Answers

GC.Collect() it'll tell it to run a collection. But, it won't collect specific objects. The GC is non-deterministic in relation to which objects are collected or not and when.

like image 105
Rich Schuler Avatar answered Mar 19 '26 10:03

Rich Schuler


No, and it wouldn't have an effect in any case:

Think about it this way. Say you had a custom class, MyBigMemoryClass, that you wanted to collect an instance of - you'd have to have some way to pass a reference of that to the garbage collector. In a theoretical world, it would be something like:

// Not valid code!
MyBigMemoryClass instance = GetMyInstance();
GC.CollectObject(instance);

However, at this point, you still have a reference to the instance of your class in the instance variable, so the object is still rooted, and not a candidate for garbage collection. The GC would see that its rooted, and leave it be.

The closest you can do is to unroot your object instance, and then have the garbage collector try to collect everything:

MyBigMemoryClass instance = GetMyInstance();
// Do something with instance
instance = null; // Unroot this, so there are (hopefully) no references to it left
GC.Collect(); // Collect everything

That being said, this is typically a very bad idea. It's much better to never call the garbage collector, and allow it to manage the memory for you. There are very few exceptions to this, mostly when working with native code, and those exceptions are typically handled better by using GC.AddMemoryPressure and GC.RemoveMemoryPressure.

like image 41
Reed Copsey Avatar answered Mar 19 '26 09:03

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!