我有一些来自 IBM 的幻灯片,名为:“从 Java 代码到 Java 堆:了解应用程序的内存使用情况” http://www.ibm.com/developerworks/library/j-codetoheap/#N101DC,也就是说,当我们使用String
代替char[]
, 有
单个角色的最大开销为 24:1!
但我无法理解这里提到的开销是什么。有人可以帮忙吗?
Source :
该数字涉及 JDK 6-32 位。
JDK 6
在 Java-7 之前的世界中,字符串被实现为指向某个区域的指针char[]
array:
// "8 (4)" reads "8 bytes for x64, 4 bytes for x32"
class String{ //8 (4) house keeping + 8 (4) class pointer
char[] buf; //12 (8) bytes + 2 bytes per char -> 24 (16) aligned
int offset; //4 bytes -> three int
int length; //4 bytes -> fields align to
int hash; //4 bytes -> 16 (12) bytes
}
于是我数了一下:
36 bytes per new String("a") for JDK 6 x32 <-- the overhead from the article
56 bytes per new String("a") for JDK 6 x64.
JDK 7
只是为了比较,在 JDK 7+ 中String
是一个持有char[]
缓冲器和一个hash
仅字段。
class String{ //8 (4) + 8 (4) bytes -> 16 (8) aligned
char[] buf; //12 (8) bytes + 2 bytes per char -> 24 (16) aligned
int hash; //4 bytes -> 8 (4) aligned
}
So it's:
28 bytes per String for JDK 7 x32
48 bytes per String for JDK 7 x64.
UPDATE
For 3.75:1
比率请参阅下面@Andrey的解释。随着字符串长度的增加,这个比例会下降到 1。
有用的链接:
-
Java 字符串和字符串相关对象的内存使用情况 http://www.javamex.com/tutorials/memory/string_memory_usage.shtml.
-
计算地图条目的内存 https://stackoverflow.com/questions/20458456/calculate-memory-of-a-map-entry/20459081#20459081- 一种获取物体大小的简单技术。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)