考虑以下代码块:
class CheckStore {
private String displayText;
private boolean state;
private String meaningfulText;
private URL url;
public CheckStore(String text, boolean state) {
this.displayText = text;
this.state = state;
}
:
:
}当我在构造函数中初始化两个变量(displayText和state)时,另外两个变量(meaningfulText和url)是否需要内存中的空间来存储null值?
Q1。如果它们确实需要空间,那么null值在内存中占用多少内存?(例如int占用4个字节)。
Q2。一个字符串在内存中占用多少空间?一个字符串需要多少内存空间?它依赖于字符串的长度吗?
发布于 2010-03-12 13:24:34
在Java语言中,null只是一个引用(基本上是一个受限指针)可以拥有的值。这意味着引用没有引用任何内容。在这种情况下,您仍然会占用引用的空间。在32位系统上为4字节,在64位系统上为8字节。但是,在您实际分配该类的实例来指向引用之前,您不会为引用所指向的类消耗任何空间。
编辑:就字符串而言,Java语言中的String为每个字符占用16位(2字节),外加少量的记账开销,这可能是未记录的和特定于实现的。
发布于 2012-11-05 21:16:13
我想补充一下:
引用类型的
对象s=(字符串)null;
Object i= (Integer)null;
System.out.println(s == i);//true
发布于 2015-05-13 07:29:20
您可以使用来获取该类的布局。(但是要小心,您可能需要对其背后的机制有更深入的了解,不要盲目相信结果,要知道这只是对当前使用的VM的估计(在我的情况下是1.7.0_76 x64 win:):
我使用CLI版本,我想正确的方法是将库包含在您的项目中,但无论如何,它似乎是这样工作的:
test>java -cp target\classes;jol-cli-0.3.1-full.jar org.openjdk.jol.Main internals test.CheckStore
Running 64-bit HotSpot VM.
Using compressed oop with 0-bit shift.
Using compressed klass with 0-bit shift.
Objects are 8 bytes aligned.
Field sizes by type: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]
Array element sizes: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]
VM fails to invoke the default constructor, falling back to class-only introspection.
test.CheckStore object internals:
OFFSET SIZE TYPE DESCRIPTION VALUE
0 12 (object header) N/A
12 1 boolean CheckStore.state N/A
13 3 (alignment/padding gap) N/A
16 4 String CheckStore.displayText N/A
20 4 String CheckStore.meaningfulText N/A
24 4 URL CheckStore.url N/A
28 4 (loss due to the next object alignment)
Instance size: 32 bytes (estimated, the sample instance is not available)
Space losses: 3 bytes internal + 4 bytes external = 7 bytes total自动压缩oops关闭时也是如此:
test>java -XX:-UseCompressedOops -cp target\classes;jol-cli-0.3.1-full.jar org.openjdk.jol.Main internals test.CheckStore
Running 64-bit HotSpot VM.
Objects are 8 bytes aligned.
Field sizes by type: 8, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]
Array element sizes: 8, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]
VM fails to invoke the default constructor, falling back to class-only introspection.
test.CheckStore object internals:
OFFSET SIZE TYPE DESCRIPTION VALUE
0 16 (object header) N/A
16 1 boolean CheckStore.state N/A
17 7 (alignment/padding gap) N/A
24 8 String CheckStore.displayText N/A
32 8 String CheckStore.meaningfulText N/A
40 8 URL CheckStore.url N/A
Instance size: 48 bytes (estimated, the sample instance is not available)
Space losses: 7 bytes internal + 0 bytes external = 7 bytes total如果您的字段为空,那么它将不会指向更多的对象,否则您还必须查看目标类型(URL和String)。(如果它们都有多个实例,这取决于您是多次使用相同的实例还是使用不同的实例)。空字段不能在内存中跳过,因为它需要在分配实例时调整其大小。因此,这些字段都是预先构造的,它们只是不引用堆中其他地方已分配的对象。
注意:如果你实现一个默认的构造函数,你会得到更多的细节,但在这个特定的例子中,大小是相同的。如果你想知道字段的顺序和填充是从哪里来的,你可以查看this article -(基本上它将对象按8字节对齐,按大小对字段排序,将相同类型分组在一起,最后引用。来自超级类型的字段首先是4字节对齐的。)
https://stackoverflow.com/questions/2430655
复制相似问题