4 ms·
(Note: the article is from 2019, but it is still relevant and interesting.) If all you're doing is deduplicating string objects in order to save memory, the ar
by smarks 4y ago
(Note: the article is from 2019, but it is still relevant and interesting.)
If all you're doing is deduplicating string objects in order to save memory, the article makes a good case to use `HashMap` or `ConcurrentHashMap` instead of `String.intern`.
The reason to use `String.intern` is in the fairly narrow case where you want to use `==` to compare strings, and some of these strings originated as string literals in Java source code. Java specifies that string literals for equal strings are always the same Java object, even if they occur in different class files that are compiled separately. This is accomplished by interning the strings, and `String.intern` provides user-level access to this same intern pool.
- chii 4y agothe guava library has an interner that does exactly what you'd want for a cache of strings, without blowing up the jvm's internal code cache (which iirc is what String.intern() uses). https://guava.dev/releases/22.0/api/docs/com/google/common/collect/Interners.html https://guava.dev/releases/22.0/api/docs/com/google/common/c...
- deleted 4y ago[deleted]
- pciexpgpu 4y agoIsn’t this concept originally from C#? (Where interning is the default behavior)
- smarks 4y agoUnlikely, as Java’s string interning behavior was specified in the first edition of the JLS (1996). This predates C# as far as I know. https://download.oracle.com/otn-pub/jcp/jls1-spec/jls1.pdf?AuthParam=1655960553_b4987d0abe9cfd0c583f90405571146d https://download.oracle.com/otn-pub/jcp/jls1-spec/jls1.pdf?A... See section 3.10.5.
- robertlagrant 4y agoThe JVM interns string literals under the hood, yes.