Strings and Garbage Collection

Spread the love

Question Description

I have heard conflicting stories on this topic and am looking for a little bit of clarity.

How would one dispose of a string object immediately, or at the very least clear traces of it?

Practice As Follows

That depends. Literal strings are interned per default, so even if you application no longer references it it will not be collected, as it is referenced by the internal interning structure. Other strings are just like any other managed object. As soon as they are no longer reference by your application they are eligible for garbage collection.

More about interning here in this question: Where do Java and .NET string literals reside?

Leave a Comment