所以我正在阅读Peter Norvig的IAQ(不经常问的问题 –
link)并偶然发现了这个问题:
You might be surprised to find that an
Object takes 16 bytes, or 4 words, in
the Sun JDK VM. This breaks down as
follows: There is a two-word header,
where one word is a pointer to the
object’s class, and the other points
to the instance variables. Even though
Object has no instance variables, Java
still allocates one word for the
variables. Finally, there is a
“handle”, which is another pointer to
the two-word header. Sun says that
this extra level of indirection makes
garbage collection simpler. (There
have been high performance Lisp and
Smalltalk garbage collectors that do
not use the extra level for at least
15 years. I have heard but have not
confirmed that the Microsoft JVM does
not have the extra level of
indirection.)
An empty new String() takes 40 bytes,
or 10 words: 3 words of pointer
overhead, 3 words for the instance
variables (the start index, end index,
and character array), and 4 words for
the empty char array. Creating a
substring of an existing string takes
“only” 6 words, because the char array
is shared. Putting an Integer key and
Integer value into a Hashtable takes
64 bytes (in addition to the four
bytes that were pre-allocated in the
Hashtable array): I’ll let you work
out why.
好吧,我显然尝试过,但我无法弄明白.在下面我只算数字:
Hashtable put创建一个Hashtable $Entry:3(开销)4个变量(3个引用,我假设是1个单词1 int).我进一步假设他意味着整数是新分配的(因此不是由Integer类缓存或已经存在),它来到2 *(3 [overhead] 1 [1 int value]).
所以最后我们最终得到了15个字或60个字节.所以我首先想到的是,作为一个内部类的Entry需要引用它的外部对象,但是它是静态的,所以这没有多大意义(确定我们必须存储一个指向父类的指针,但我会认为信息由VM存储在类头中.
只是空闲的好奇心,我很清楚这一切都取决于实际的JVM实现(在64位版本上的结果会有所不同),但我仍然不喜欢我无法回答的问题:)
编辑:只是为了让这一点更清楚:虽然我很清楚更紧凑的结构可以给我们带来一些性能上的好处,但我同意一般在这里担心几个字节或者浪费时间.我肯定不会因为这里的几个字节开销而停止使用Hashtable,就像我不会使用普通字符数组而不是字符串(或开始使用C).学习更多关于Java / JVM内部的内容纯粹是学术上的兴趣:)