Java类的内存对齐

2023-12-19

假设我在 64 位机器上编译 C 程序gcc。我假设sizeof(int)是 8 个字节,并且sizeof(char)是1字节。

由于内存对齐,以下结构:

struct example{
    int a;
    char c;
}

实际上大小不是 9 个字节,而是 16 个字节(两倍sizeof(int)),因此它的起始地址和结束地址都可以是字大小的倍数(此处假设为 8 个字节)。

我想知道下面的类在 Java 8 中会有多大:

class Node {
    int val;
    Node left, right;
    boolean flag;
 }

我基本上不确定我们是否会以 8 字节或 4 字节的倍数对齐。


您可以使用jol http://openjdk.java.net/projects/code-tools/jol/了解对象的确切布局。这是 Node 类的程序输出(在 Oracle JDK 1.8.0_121 64 位上):

# 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.example.Node object internals:
OFFSET  SIZE    TYPE DESCRIPTION                    VALUE
     0     4         (object header)                01 00 00 00 (00000001 00000000 00000000 00000000) (1)
     4     4         (object header)                00 00 00 00 (00000000 00000000 00000000 00000000) (0)
     8     4         (object header)                70 22 01 f8 (01110000 00100010 00000001 11111000) (-134143376)
    12     4     int Node.val                       0
    16     1 boolean Node.flag                      false
    17     3         (alignment/padding gap)        N/A
    20     4    Node Node.left                      null
    24     4    Node Node.right                     null
    28     4         (loss due to the next object alignment)
Instance size: 32 bytes
Space losses: 3 bytes internal + 4 bytes external = 7 bytes total

所以,对齐是8字节。

请注意,这是特定于平台的。您不应该过分依赖此信息。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java类的内存对齐 的相关文章

随机推荐