Java中String的内存使用情况 [英] Memory usage of String in Java

查看:55
本文介绍了Java中String的内存使用情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中有一个包含字符串的对象.我很好奇字符串的内存使用情况如何工作.我正在尝试优化程序的内存使用量,该应用程序将包含约10000个此类对象.对于诸如"Hello World"之类的字符串,内存使用量将是多少?

I have an object in Java which contains a String. I am curious how the memory usage of a String works. I'm trying to optimize memory usage for my program and the application will have about 10000 such objects. For a String such as "Hello World" what would the memory usage be?

推荐答案

Java每个字符使用两个字节 * ,因此您需要将字符数乘以2才能得到一个近似值.除了存储有效载荷"外,您还需要考虑分配给字符串引用的空间,该空间通常等于目标体系结构上的指针大小,字符串长度的空间, int和缓存的哈希码的空间,即另一个int.

Java uses two bytes per character *, so you would need to multiply the number of characters by two to get a rough approximation. In addition to the storage of the "payload", you would need to account for the space allocated to the reference to your string, which usually equals to the size of a pointer on your target architecture, the space for the length of the string, which is an int, and the space for the cached hash code, which is another int.

由于"Hello World"为11个字符长,因此我估计在具有32位指针的计算机上其大小为2 * 11 + 4 + 4 + 4 = 34字节,或者2 * 11 + 8 + 4 + 4 =具有64位指针的计算机上为38个字节.

Since, "Hello World" is 11 characters long, I would estimate its size as 2*11+4+4+4=34 bytes on computers with 32-bit pointers, or 2*11+8+4+4=38 bytes on computers with 64-bit pointers.

注意:此估计未考虑内部字符串常量的影响.当字符串为已嵌入时,所有引用保留给字符串的字符串共享相同的有效负载,因此,每个附加字符串实例的额外内存是引用的大小(即目标体系结构上的指针大小).


* 除非使用-XX:+UseCompressedStrings选项,否则不需要UTF-16的字符串将使用UTF-8编码.

Note: this estimate does not consider the effects of interning string constants. When a string is interned, all references to the interned string share the same payload, so the extra memory per additional instance of an interned string is the size of a reference (i.e. the pointer size on the target architecture).


* Unless the -XX:+UseCompressedStrings option is used, in which case the strings that do not need UTF-16 use UTF-8 encoding.

这篇关于Java中String的内存使用情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆