3 ms·
> Also, since Strings are immutable Java can do some optimizations like representing the same string value as just a single underlying instance even if multiple
by chrisseaton 6y ago
> Also, since Strings are immutable Java can do some optimizations like representing the same string value as just a single underlying instance even if multiple instances of that String are created in code.
I thought the JVM stopped doing that many years ago?
- hn_throwaway_99 6y agoNo, that's not correct. String literals in code are always interned, and you can still call String.intern() on any String instance. What you may be referring to is that interned Strings are stored in the head, while they used to be stored in the Permanent Generation: https://stackoverflow.com/a/10579062 https://stackoverflow.com/a/10579062
- chrisseaton 6y ago> No, that's not correct. See the commit for yourself! They removed the sharing between string values when you created a substring a while ago. https://github.com/openjdk/jdk/commit/f55750d05a04484b719220f21e34c05017f001fd https://github.com/openjdk/jdk/commit/f55750d05a04484b719220...
- hn_throwaway_99 6y agoSorry, yes, we were talking about different things. Calling String.substring() used to not copy the original char array, and would instead just store an offset and length in the new String, but still point to the char array of the original String. This could cause memory leaks, and the commit you referenced fixes that. I was referring to String interning, where literals defined in code are only created once even if they are duplicated, and the API provides String.intern() to get the "canonical" instance of a String.