'How much memory does a string use in Java 8?

I read a lot about memory allocation for Strings lately and can't find any details if things are the same with Java 8.

How much memory space would a String like "Alexandru Tanasescu" use in Java 8? I use the 64bit version.



Solution 1:[1]

If you look at the Oracle Java 8 sources, you have:

A char value[] and an int hash. A char is 2 bytes, and an int is 4 bytes.

So wouldn't the answer be yourstring.length * 2 + 4?

No. Every object had overhead. An array stores its dimensions, for example. And both the array (an object) and the string will incur extra memory from the garbage collector storing information about them.

There is no reliable way to calculate this, because AFAIK each JRE and JDK has no obligation to the size of object overhead.

Solution 2:[2]

"Alexandru Tanasescu" uses 104 bytes. This is how to get the size

    long m0 = Runtime.getRuntime().freeMemory();
    String s = new String("Alexandru Tanasescu");
    long m1 = Runtime.getRuntime().freeMemory();
    System.out.println(m0 - m1);

Note: run it with -XX:-UseTLAB option

Solution 3:[3]

According to the following JEP: http://openjdk.java.net/jeps/254

The current implementation of the String class stores characters in a char array, using two bytes (sixteen bits) for each character.

In Java SE 9 this might change.

Note however, since this is a JEP not a JSR (and it mentions implementation), I understand, that this is implementations specific and not defined by the JLS.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ryan Goldstein
Solution 2 Evgeniy Dorofeev
Solution 3 Puce