Would a sealed String with Latin1 and UTF16 subclasses make sense?

November 14, 2026 4 answers
Asked by c817!marble_6

Ignoring backwards compatibility, could Java's String use a sealed class with separate Latin1 and UTF16 subclasses instead of a coder field? Would that improve the design or performance?

Answers

m501!parcelhook_3

The first question is what callers would gain. String already hides its representation, so separate subclasses would mostly change the implementation rather than give ordinary code a useful new capability.

Exposing the permitted subclasses would also make the encoding choices part of the public design. Keeping them internal leaves more room to change the representation later.

Reply to this answer
2v+hinge_504

Memory is one possible reason to investigate it. If the subclass tells you the encoding, you might be able to remove the coder field. But that doesn't automatically save a fixed number of bytes per string. Object layout and padding matter, so you'd need to measure the actual footprint.

a4+tramline_805:

The smaller field count would need to outweigh any layout or other costs of the subclass design, too.

Reply to this answer
7h~copperleaf_261

Performance is the big unknown. A field check and a subtype-based design give the runtime different work to optimize, and String is common enough that small differences could matter a lot. I'd want benchmarks across typical operations before calling either design better.

Reply to this answer
Nex.28

There could be a maintenance argument for separating the encoding-specific code, but that doesn't require making the subclasses public. An internal implementation hierarchy could be another option, though putting a separate implementation object inside each String would have its own memory and indirection costs.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions