[英]Use of Primitive `byte` increased space occupied when compared to Primitive `int`
[英]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
字段(或char
或short
字段)的类,那么这些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
很清楚地表boolean
和byte
占用一个字节作为对象字段。
正如您所期望的, char
和short
是2个字节, int
和float
是4个字节, long
和double
是8个字节。
https://stackoverflow.com/a/14782255/869736解释了有关Dalvik的一些细节,包括目前像byte
这样的小字段实际上是用4个字节实现的。 请记住,这些细节都将成为虚拟机相关的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.