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 ?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With