Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is const string eligible for garbage collection?

Tags:

c#

.net

I have a relatively large strings that will not change during my program run. Is it wise to mark them as const string (in order to gain some imaginary performance benefits) ? Will the memory allocated for these string will be eventually garbage collected ?

like image 935
Petar Petrov Avatar asked Oct 29 '09 21:10

Petar Petrov


People also ask

Is string constant pool eligible for garbage collection?

6. Garbage Collection. Before Java 7, the JVM placed the Java String Pool in the PermGen space, which has a fixed size — it can't be expanded at runtime and is not eligible for garbage collection.

Do strings get garbage collected?

They will be garbage collected if the GC finds them to be unreachable. In practice, the String objects that correspond to string literals typically do not become candidates for garbage collection. This is because there is an implicit reference to the String object in the code of every method that uses the literal.

Could you make sure a const value is garbage collected?

With a const variable declaration, you can't assign to the variable something little like "" or null to clear its contents. That's really the only difference in regard to memory management. Automatic garbage collection is not affected at all by whether it is declared const or not.

Which objects are eligible for garbage collection?

An object is eligible to be garbage collected if its reference variable is lost from the program during execution. Sometimes they are also called unreachable objects. What is reference of an object? The new operator dynamically allocates memory for an object and returns a reference to it.


1 Answers

No it will not. Const strings are stored in metadata and hence are not ever collected unless the containing assembly is removed from the process. This will only happen on AppDomain unload. All uses of this string are simply references to this memory.

like image 99
JaredPar Avatar answered Sep 28 '22 11:09

JaredPar