java中能用多少字符,字符串在Java 8中使用了多少内存?

本文详细探讨了Java 8中字符串内存使用的变化,重点在于与Java 7的比较。Java 8移除了长度和偏移量字段,但计算内存占用的基本原理保持不变。了解内存分配时,需考虑字符数组、哈希码缓存等因素。一个如'Aleksandru Tanasescu'的字符串在Java 8中,由于缺失部分字段,内存占用减少8 bytes。
摘要由CSDN通过智能技术生成

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.

解决方案

Java7 or lower

Minimum String memory usage :

(bytes) = 8 * (int) ((((no chars) * 2) + 45) / 8)

So

80 = 8 * (int) ((((19) * 2) + 45) / 8)

Understanding String memory usage (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.

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.

Java8.

Java 8 does not have the offset and length anymore. Only hash and the CharArray.

@Thomas Jungblut

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.

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值