<分区>
如果我在一个类中需要 8 个 boolean 成员变量,Java 是否有效地将它们全部放在一个字节中?或者它会为每个使用一个字节吗?换句话说,内存占用是否不同:
boolean a;
boolean b;
boolean c;
boolean d;
boolean e;
boolean f;
boolean g;
boolean h;
对比
public static final int a = 0x01;
public static final int b = 0x02;
public static final int c = 0x04;
public static final int d = 0x08;
public static final int e = 0x10;
public static final int f = 0x20;
public static final int g = 0x40;
public static final int h = 0x80;
byte flags;
我问是因为我将实例化这些对象中的很多。因此,让它占用 1 个字节而不是 8 个字节的内存将是一个显着的节省。
更新:这绝对类似于列出 boolean 值存储在 int 中的链接问题(感谢您提供这些链接,抱歉我在提问之前没有找到它们)。这个问题有点不同,因为它提出了使用字节和位标志的特定替代方案。我不知道这是否足以让这个问题不再重复。
更新 2: 我刚刚使用 SizeofUtil 运行了这个并发现以下内容。 8 个 boolean 值需要 24 个字节/对象或 3 个字节/boolean 值。单字节方法需要 10 个字节/对象。我会理解 8 将一个字节扩展为 native int(我在 64 位系统上)。但是其他 2 个字节是什么?