Java7或更低版本
最小字符串内存使用量:
(bytes) = 8 * (int) ((((no chars) * 2) + 45) / 8)
所以
80 = 8 * (int) ((((19) * 2) + 45) / 8)
了解字符串内存使用情况(SOURCE)
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.
如果String包含19个字符,那么String对象本身仍然需要24个字节.但是现在char数组需要12个字节的头,加上19 * 2 = 34个字节的十七个字符.由于12 34 = 46不是8的倍数,我们还需要舍入到8(48)的下一个倍数.因此,我们的19个字符的字符串将使用56 24 = 80个字节.
Java8.
Java 8 does not have the offset and length anymore. Only hash and the CharArray.
07001
>一个char数组 – 因此一个单独的对象 – 包含实际的字符;
>字符串开始的数组中的整数偏移量;
>字符串的长度;
>另一个int用于缓存计算哈希码.
所以在Java8中,为字符串计算内存的方式保持不变,但由于缺少的偏移量和长度,您必须减少8个字节.