Java中String的内存使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19776463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 20:07:21  来源:igfitidea点击:

Memory usage of String in Java

javastringmemory

提问by RagHaven

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 中有一个包含字符串的对象。我很好奇 String 的内存使用是如何工作的。我正在尝试为我的程序优化内存使用,应用程序将有大约 10000 个这样的对象。对于诸如“Hello World”之类的字符串,内存使用量是多少?

回答by dasblinkenlight

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.

Java 每个字符使用两个字节*,因此您需要将字符数乘以 2 以获得粗略的近似值。除了“有效负载”的存储之外,您还需要考虑分配给字符串引用的空间,这通常等于目标架构上指针的大小,字符串长度的空间,这是一个int,以及缓存哈希码的空间,这是另一个int

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.

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

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).

注意:这个估计没有考虑字符串常量的影响。当字符串被interned 时,对 interned 字符串的所有引用共享相同的有效负载,因此每个附加的 interned 字符串实例的额外内存是引用的大小(即目标架构上的指针大小)。



**除非使用该-XX:+UseCompressedStrings-XX:+UseCompressedStrings选项,在这种情况下不需要UTF-16 的字符串使用UTF-8 编码。