一个布尔值的Java中的数组不是一个独立的变量更小? [英] Is an array of one boolean in Java smaller than a standalone variable?
问题描述
我对SO搜索都失败了我,所以如果这是一个重复的,请重定向我。
My searches on SO have failed me, so if this is a duplicate, please redirect me.
有了这样的方式,我的问题:我了解到,从经验和浏览,这样一个Java 布尔
存储为一个32位的 INT
如果你声明它作为一个独立的价值,但作为一个8位字节
。我的问题,在这里,如下:哪个更高效的内存?难道数组的元数据,使之更大的内存比其他?
With that out of the way, my question: I learned, from experience and browsing SO that a Java boolean
is stored as a 32-bit int
if you declare it as a standalone value, but as an 8-bit byte
if you declare it within an array. My question, here, is as follows: Which is more memory efficient? Does the meta data of the array make it bigger in memory than the alternative?
boolean oneVariable = false, oneArray[] = {false};
推荐答案
阵列的元数据包括用于开销阵列的长度为8个字节(通用于所有的对象)和4个字节(32位)(特定于一个32位JVM阵列对象)。
The "meta data" of the array includes 8 bytes for overhead (common to all objects) and 4 bytes (32 bits) for the length of the array (specific to array objects) on a 32-bit JVM.
在8字节的倍数此外,对象分配内存,所以尽管你只需要12字节的开销+ 1字节为布尔,你会最终使用16字节的内存为您的数组对象。
Additionally, objects are allocated memory in 8-byte multiples, so even though you only need 12 bytes of overhead + 1 byte for the boolean, you'll end up using 16 bytes of memory for your array object.
在除了16个字节本身占用的对象,你将需要4个字节为对象的内存地址,共计20个字节的内存,您的布尔存放在数组中。
In addition to the 16 bytes the object itself will take up, you'll need 4 bytes for the memory address of the object, totalling 20 bytes of memory to store your boolean in an array.
因此,该阵列为约5倍昂贵单个布尔值。
So, the array is about 5 times as expensive for a single boolean.
这篇关于一个布尔值的Java中的数组不是一个独立的变量更小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!