簡體   English   中英

當間接在數組內時,字節原語是否成為內存中的字節?

[英]Does a byte primitive become a byte in memory when indirectly inside an array?

我聽說一個字節本身在內存中占用4個字節,而一個字節數組中的一個字節占用1個字節,但是在一個數組內的對象內的字節成員變量呢?

class SomeObject {
    byte iBite;
}

public static void main(String[] args) {
    SomeObject[] objs = ...
}

每個SomeObject的iBite變量在內存中只有1個字節嗎?

作為局部變量的字節實現為int ,因此需要4個字節。

作為字段的字節(如示例中所示)占用1個字節的內存,但內存中的類在例如HotSpot JVM上向上舍入為8個字節的倍數。 也就是說,如果你有一個具有多個byte字段(或charshort字段)的類,那么這些char將更有效地使用內存。

數組相似:每個byte占用1個字節,但整個數組將在例如HotSpot JVM上向上舍入為8個字節的倍數。

您可以使用http://openjdk.java.net/projects/code-tools/jol/手動試驗。 如果您使用它,例如,打開

public static class A {
    boolean f;
    byte g;
    int h;
}

我明白了

Running 64-bit HotSpot VM.
Using compressed oop with 3-bit shift.
Using compressed klass with 3-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]

org.openjdk.jol.samples.JOLSample_01_Basic.A object internals:
 OFFSET  SIZE    TYPE DESCRIPTION                    VALUE
      0    12         (object header)                N/A
     12     4     int A.h                            N/A
     16     1 boolean A.f                            N/A
     17     1    byte A.g                            N/A
     18     6         (loss due to the next object alignment)
Instance size: 24 bytes (estimated, the sample instance is not available)
Space losses: 0 bytes internal + 6 bytes external = 6 bytes total

很清楚地表booleanbyte占用一個字節作為對象字段。

正如您所期望的, charshort是2個字節, intfloat是4個字節, longdouble是8個字節。

https://stackoverflow.com/a/14782255/869736解釋了有關Dalvik的一些細節,包括目前像byte這樣的小字段實際上是用4個字節實現的。 請記住,這些細節將成為虛擬機相關的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM