back

by MrBuddyCasino·11y ago·view on hn ↗
Actually, no. 90% of the problems with strings in any language is somebody screwing up the character encoding, usually out of ignorance.

The fact that every object in Java has some overhead and probably needs some padding for alignment is utterly irrelevant. But since you asked:

- 8 bytes generic object overhead per String

- 4 bytes for the char[] ref

- 12 bytes for the char[] itself, if non-null, plus probably 4 bytes padding

- 12 bytes for length, offset and hash code int fields (3*4 bytes)

- and 2 bytes per character stored

So I guess 40 bytes for the empty string should be about it. Happy?

My customer's servers have usually 8Gb or RAM, 16Gb is becoming the norm. Nobody cares anymore. Maybe its important in your field, I don't know. No mine though.

So did I ever need to know this piece of trivia? No.

Did I have to fix someone else's code which was relying on the platform default encoding? Lots of times.

PP: actually in C, you get the usually security nightmares on top of the encoding stuff.

3 comments
> - and 2 bytes per character stored

No, 2 bytes per code unit. A single UTF-16 character requires one or two code units. So a single "character" (code point in Unicode terminology) is either 2 or 4 bytes in Java. Additionally, a single Unicode character can require multiple code points.

What many C++ programmers often forget is that most of those overheads exist in C++ as well. They are only less visible. String length? Check. Char array header? 8-16 bytes reserved by the allocator and additional hidden length field created by c++ compiler. Array pointer: another 4 or 8 bytes. I guess the only thing c++ saves is for the fact the string object itself can be stack allocated. That's just 8 bytes for the object header saved.
Very late reply, but to clarify, what I meant was not 'was is the size of a string' but 'what is sizeof(char)'. Meaning, if your char is a fixed size it can't represent all characters or is wasteful in 95% of all cases (8, 16 or 32 bit) or if it's variable length the formal complexity goes up for a number of often-used operations.
> My customer's servers have usually 8Gb or RAM, 16Gb is becoming the norm.

Does the cache sizes not matter? Honest question.

Thats not so easy to answer. It starts to matter a lot when you get into very high performance architectures (think disruptor, anything requiring lots of mechanical sympathy, highly contended memory access etc.), but usually you're waiting for the database or the network anyway.

Supposing you meant memory bloat compared to C, increased developer productivity is almost always more important. Things like memory access patterns can be important when you are interested in optimizing hot loops, but not generally.