If I use String.intern() to improve performance as I can use “==” to compare interned string, will I run into garbage collection issues? How does the garbage collection mechanism of interned strings differ from normal strings ?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In fact, this not a garbage collection optimisation, but rather a string pool optimization.
When you call
String.intern(), you replace reference to your initial String with its base reference (the reference of the first time this string was encountered, or this reference if it is not yet known).Prior to Java 7 interned strings were allocated in PermGen space. This would become a garbage collector issue once your string is of no more use in application, since the interned string pool is a static member of the String class and will never be garbage collected. From Java 7 onward the interned strings are allocated on the Heap and are subject to garbage collection.
As a rule of thumb, i consider preferrable to never use this intern method and let the compiler use it only for constants Strings, those declared like this :
This is better, in the sense it won’t let you do the false assumption
==could work when it won’t.Besides, the fact is
String.equalsunderlyingly calls==as an optimisation, making it sure interned strings optimization are used under the hood. This is one more evidence==should never be used on Strings.