Jas*_*son 5 java memory-alignment
假设我在64位机器上编译C程序gcc.我假设这sizeof(int)是8个字节,并且sizeof(char)是1个字节.
由于内存对齐,以下结构:
struct example{
int a;
char c;
}
Run Code Online (Sandbox Code Playgroud)
实际上大小不是9个字节,而是16个(两次sizeof(int)),因此它的起始地址和结束地址都可以是字大小的倍数(这里假定为8个字节).
我想知道下面的类在Java 8中有多大:
class Node {
int val;
Node left, right;
boolean flag;
}
Run Code Online (Sandbox Code Playgroud)
我基本上不确定我们是否会以8或4字节的倍数对齐.
Zhe*_*lov 11
您可以使用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
Run Code Online (Sandbox Code Playgroud)
因此,对齐是8个字节.对于32位JVM,它将是4个字节.
请注意,这是特定于平台的.你不应该太依赖这些信息.
| 归档时间: |
|
| 查看次数: |
2055 次 |
| 最近记录: |