3 ms·
> Wait, why would interned immutable strings require more instructions when doing regular string access? Java automatically interns static strings (e.g. from c
by amiga386 2mo ago
> Wait, why would interned immutable strings require more instructions when doing regular string access?
Java automatically interns static strings (e.g. from class files), but does not automatically intern dynamically-allocated strings, e.g. new String(charArray)
If you want it interned, you have to intentionally call e.g. new String(...).intern(). If you do this on every string you work with, you can then reliably use reference equality instead of value equality, e.g. given char[] abc = {'a','b','c'}; then new String(abc) != new String(abc) != "abc" but new String(abc).intern() == new String(abc).intern() == "abc"
But if you're interning every string, you're doing extra work to maintain that string pool, and adding extra pressure on the GC, and potentially you'll be re-interning strings a lot depending on how many times they end up no longer referenced by the time GC runs.
- vanderZwan 2mo agoThanks to both of you for explaining, I thought Java and JavaScript would have similar behavior here and did not know .intern() had to be manually invoked in the former. Just to clarify where I started from: JS has the notion of String Primitives and String Objects[0], and concatenating two string primitives results in another string primitive. It's as if it always calls .intern(). Except, since from a user perspective there is no option to not intern it, JS implementations are free to do optimizations that don't seem available to Java. Like avoiding heap allocation for provably short-lived strings in the first place, and not interning them if they are never compared (I don't actually know if it does those optimizations, but I imagine it shouldn't be too hard to prove these things with many short functions). [0] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_primitives_and_string_objects https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...