r/java • • Jul 19 '26

Disregarding backwards compatibility, would it make sense for String to be a sealed class?

like public sealed class String permits Latin1String, Utf16String instead of the private final byte coder; field

20 Upvotes

26 comments sorted by

View all comments

Show parent comment

18

u/hoat4 Jul 19 '26

Not OP, but memory usage reduction could be an advantage of subtyping: if no "coder" field needed, it's 8 byte saving for each String instance.

Another reason could be easier maintenance of java.lang.String for JDK developers.

7

u/FirstAd9893 Jul 19 '26

There's also the hashIsZero field, which will be combined with the coder byte into a single 4 byte field, not an 8 byte field. In order to reduce memory overhead further, both the coder and hashIsZero fields would need to be dropped.

When the coder field was added, the goal was to reduce memory overhead by using Latin-1 instead of UTF-16 in most cases. It's still a win overall.

1

u/Liskar-dev Jul 29 '26

it's 8 byte saving for each String instance

It's 4 bytes, because Compressed OOPs is on by default

-2

u/koflerdavid Jul 19 '26

It sounds like the debate about Pascal-style (length field) and C-style (\0 terminated) strings again. I guess it's simply not worth it in many cases. 8 bytes are really not that much compared to the length of most strings.

1

u/mikeblas Oct 26 '26

Oh! I've always been curious about this, and it sounds like you'll be able to help me: How long are most strings?

0

u/koflerdavid Oct 27 '26

8 bytes are eight characters in ISO-8859-1 encoding or four UTF codepoints in UTF-16. I hazard that most strings are rather longer, unless we're talking about specific applications or benchmarks where it could pay off to think about a more efficient encoding.