logoalt Hacker News

vanderZwanyesterday at 10:23 PM2 repliesview on HN

> requiring more instructions for string access

Wait, why would interned immutable strings require more instructions when doing regular string access? You can still point to the start of a zero-terminated C-string, it just requires storing extra metadata like lenght and a string hash somewhere. Which can be done at the negative indices of said pointer.

Or do you refer to the extra rolling-hash pass needed when concatenating two strings to verify if it would result in an already-interned one? Because yes, that's one extra rolling hast pass over the appended string the first time a string is constructed, but after that doing so again likely saves memory and construction time, because any concatenation that would result in an already interned string would avoid actual memory allocation and copying of the string's characters.

Plus string comparisons become cheap O(1) pointer comparisons this way, which is really nice in many use-cases.

And that's not even considering more advanced tricks like interning short strings in the 64-bit word of the pointer to the string itself, relying on the fact that modern memory allocators never return an address with the lsb set, so it can be used to flag it as such[0].

[0] https://squoze.org/


Replies

amiga386today at 12:43 AM

> 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.

Someonetoday at 7:15 AM

> Wait, why would interned immutable strings require more instructions when doing regular string access

Sorry, I wasn’t precise. Accessing them won’t take more instructions, but setting them up does.

> Or do you refer to the extra rolling-hash pass needed when concatenating two strings to verify if it would result in an already-interned one?

I don’t think the JVM does that.