Java - null变量是否需要内存空间

时间:2010-03-12 05:19:49

标签: java

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;
    }
    :
    :
}

由于我在构造函数中只初始化了两个变量(displayTextstate),其余两个变量(meaningfulTexturl将具有值{ {1}})将需要内存空间来存储null值。

Q1。我认为他们需要空间。如果他们愿意,那么null值在内存中占用多少内存(如null占用4个字节)。

Q2。字符串在内存中占用多少空间。我想这将取决于字符串的长度。那么字符串需要多长的空间长度呢?

4 个答案:

答案 0 :(得分:54)

在Java中,null只是引用(基本上是受限制的指针)可以具有的值。这意味着参考没有任何意义。在这种情况下,您仍然占用参考空间。这是32位系统上的4个字节或64位系统上的8个字节。但是,在实际分配该类的实例以指向引用之前,您不会为引用所指向的类占用任何空间。

编辑:就字符串而言,Java中的String为每个字符占用16位(2字节),加上少量的簿记开销,这可能是未记录的,并且是特定于实现的。

答案 1 :(得分:11)

我想补充一下:

  1. 引用类型的变量将初始化为空值。
  2. null不是对象。因为(null instanceof Object)等于false
  3. JVM中只有一个空值。无论有多少变量引用null。

    Object s =(String)null;

    对象i =(整数)null;

    System.out.println(s == i); // true

答案 2 :(得分:4)

You can use jol to get the layout of that class. (However be careful, you might need a deeper understanding on the mechanics behind it, don't blindly trust the result and be aware it is just an estimate for the currently used VM (1.7.0_76 x64 win in my case:):

I use the CLI version I guess the proper method would be to include the library in your project, but anyway, it seems to work this way:

 <div id="pecheislandrear" class="panelHidden" style="position:fixed;left:50%;margin-left:-136px;top:50%;margin-top:-211px;
        z:1;width:272px;height:422px;">
    <div id="panel0" style="position:absolute;left:0px;top:12px;width:272px;
        height:54px;overflow:hidden;">
      <p class="Body panelP-5"><span class="panelTitle">Peche Island Rear Range</span></p>
    </div>
    <div style="position:absolute;left:24px;top:229px;width:232px;height:136px;overflow:hidden;">
      <p class="Normal"><span class="panelDesc">Range lights were 
established off Peche island in 1898. Pile clusters, they were 
repeatedly swept away by ice until 1908 when they were replaced by 
permanent iron and steel structures on cribs. An explosion destroyed the
front range in 1927, and the rear range was leaning so badly it was 
replaced with a modern structure in 1983. The tower was moved to Marine 
City where it can now be seen on the waterfront.</span></p>
    </div>
    <a onclick="var w = window.open(this.href,'_blank','width=1400,directories=yes,location=yes,menubar=yes,resizable=no,
        scrollbars=yes,status=yes,toolbar=yes'); if( w != null ){ w.focus(); }; return false;" href="http://www.lighthousefriends.com/light.asp?ID=165" target="_blank" class="panelOBJ-12 ActiveButton buttonHeight" style="position:absolute;left:84px;top:372px;width:104px;height:21px;">
      <span>Learn&nbsp;More</span>
    </a>
    <img alt="photo" src="LakeErie1_files/pecherear.jpg" onclick="hidePanels()" style="position:absolute;z:2;left:38px;top:73px;width:201px;height:151px;">
 </div>

and the same with automatic compressed oops off:

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

Those are only the layouts for the object itself if your fields are null, then it will not point to more objects, otherwise you have to look at the target types (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 and URL) as well. (And if you have multiple instances of all of them it depends if you use the same multiple times or different ones). An null field cannot be skipped in memory, as it would require the instance to be resized when it is assigned. So the fields are all pre-constructed, they just do not reference allocated objects somewhere else on the heap.

NB: you get some more details if you implement a default constructor, but the sizing in this specific case would be the same. In case you wonder where the sequence and padding of fields is coming from, you can check this article - (basically it aligns objects on 8 bytes, sorts fields by size, groups same type together, references last. Fields from super types are first, 4 byte aligned.)

答案 3 :(得分:0)

Null表示0.在内存中通常有一个null定义。每当使用编程语言指向它时。一切都指向同一个地方。这意味着NULL只消耗了一个4字节的内存。然后无论什么指向它都不会消耗更多的内存。 NULL的定义是特定于语言的,但定义为void * ptr = 0;在C和C ++中很常见。 JAVA必须以类似的方式定义它。不可能指向任何东西。你必须指出一些事情。但我们定义了一个共同的东西,一切都指向它只消耗那个空间。