How much memory does a string consume in Java

Understanding String memory usage

To understand the above calculation, we need to start by looking at the fields on a String object. A String contains the following:

  • a char array— thus a separate object— containing the actual characters;
  • an integer offset into the array at which the string starts;
  • the length of the string;
  • another int for the cached calculation of the hash code.

This means even if the string contains no characters, it will require 4 bytes for the char array reference, plus 3*4=12 bytes for the three int fields, plus 8 bytes of object header. This gives 24 bytes (which is a multiple of 8 so no “padding” bytes are needed so far). Then, the (empty) char array will require a further 12 bytes (arrays have an extra 4 bytes to store their length), plus in this case 4 bytes of padding to bring the memory used by the char array object up to a multiple of 16. So in total, an empty string uses 40 bytes.

If the string contains, say, 17 characters, then the String object itself still requires 24 bytes. But now the char array requires 12 bytes of header plus 17*2=34 bytes for the seventeen chars. Since 12+34=46 isn’t a multiple of 8, we also need to round up to the next multiple of 8 (48). So overall, our 17-character String will use up 48+24 = 72 bytes.

In general this is the formula to calculate the minimum number of bytes a given string would take :

 

minimum String memory usage (bytes) = 8 * (int) ((((no chars) * 2) + 45) / 8)

Since Java 7 implementation of string class has changed. It no longer stores offset and count, hence you can subtract 8 from the above formula for the strings created in Java 7 and later.

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *