Size of empty Java String

Viewed 6284

I heard a colleague say that I would pay "24 bytes" if I dropped a String member in a Java class, even if the String is empty. Is that accurate? Is it the same for Integer, Float, Double? (as opposed to int, float, double, which would be only 4, 4 and 8 bytes each).

4 Answers

String is composed out of object header (2 words on HotSpot, 3 on J9), int field and char array reference. Char array itself is composed out of header, int field and the rest of array. Everything is padded to 8 bytes. Usually, chars are encoded with 2 bytes per char. Some JVMs can use alternative encodings for char. At one point J9 could encode strings in UTF8. Modern HotSpot will use 1 byte per char if string is composed of simple chars (essentially 1 byte encoded glyphs of UTF-8, like english alphabet, numbers and such). Otherwise it uses 2 bytes per char for whole array.

So deep size of empty string size is thus:

  • 32 bytes on 32 bit HotSpot (16 bytes for String, 16 bytes for char[])
  • 56 bytes on 64 bit HotSpot (32 bytes for String, 24 bytes for char[])
  • 40 bytes on 64 bit HotSpot with compressed references (24 bytes for String, 16 bytes for char[])

Commonly, empty char array will not be allocated as it's value will be inferred. After all all empty char arrays are equal. So actual penalty for an empty string will be a shallow String size; which is 24 bytes for most common situation today (64 bit HotSpot with compressed ref).

IBM J9 JVM has bigger object header and it will allocate somewhat more.

Related