字符串在 Java 8 中使用多少内存? [英] How much memory does a string use in Java 8?
问题描述
我最近阅读了很多关于字符串内存分配的内容,如果与 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.
像 "Alexandru Tanasescu"
这样的字符串在 Java 8 中使用多少内存空间?我使用的是 64 位版本.
How much memory space would a String like "Alexandru Tanasescu"
use in Java 8?
I use the 64bit version.
推荐答案
Java7 或更低版本
最小字符串内存使用量:
Java7 or lower
Minimum String memory usage :
(bytes) = 8 * (int) ((((no chars) * 2) + 45) / 8)
所以
80 = 8 * (int) ((((19) * 2) + 45) / 8)
<小时>
了解字符串内存使用(来源强>)
要理解上面的计算,我们需要从查看 String 对象上的字段开始.一个字符串包含以下内容:
To understand the above calculation, we need to start by looking at the fields on a String object. A String contains the following:
- 一个字符数组——因此是一个单独的对象——包含实际的字符;
- 字符串开始的数组中的整数偏移量;
- 字符串的长度;
- 另一个用于缓存计算哈希码的 int.
这意味着即使字符串不包含字符,也需要 4 个字节用于 char 数组引用,加上 3*4=12 个字节用于三个 int 字段,加上 8 个字节的对象头.这给出了 24 个字节(这是 8 的倍数,因此到目前为止不需要填充"字节).
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).
然后,(空)char 数组将需要另外 12 个字节(数组有额外的 4 个字节来存储它们的长度),在这种情况下,加上 4 个字节的填充以将 char 数组对象使用的内存增加到16 的倍数.因此,空字符串总共使用 40 个字节.
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=38 个字节的 17 个字符.由于 12+38=50 不是 8 的倍数,因此我们还需要四舍五入到下一个 8 的倍数 (56).所以总的来说,我们 19 个字符的 String
将使用 56+24 = 80 个字节.
If the String
contains, say, 19 characters, then the String object itself still requires 24 bytes. But now the char array requires 12 bytes of header plus 19*2=38 bytes for the seventeen chars. Since 12+38=50 isn't a multiple of 8, we also need to round up to the next multiple of 8 (56). So overall, our 19-character String
will use up 56+24 = 80 bytes.
Java 8 不再有 offset
和 length
.只有 hash
和 CharArray
.
@Thomas Jungblut一个>
Java 8 does not have the
offset
andlength
anymore. Onlyhash
and theCharArray
.
@Thomas Jungblut
- 一个字符数组——因此是一个单独的对象——包含实际的字符;
一个整数偏移量到字符串开始的数组中;字符串的长度;- 另一个用于缓存计算哈希码的 int.
因此,在 Java8 中,计算字符串内存的方法保持不变,但由于缺少 offset
和 length
,您必须减去 8 个字节.
So, in Java8 the way to calculate memory for strings remains same but you must subtract 8 bytes less due to the missing offset
and length
.
这篇关于字符串在 Java 8 中使用多少内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!