本帖最后由 kerner 于 2014-11-23 10:15 编辑
1bit就可以表示记录该变量的值,但是它的大小没有严格的定义,它可能为int,也可能是bit,byte。
参考:1-----> http://www.iteye.com/problems/88825boolean
值为 1/0 逻辑上占1bit 但实际上要看虚拟机 并没有精确定义;如hotspot: boolean i = true; //此时在栈上分配,为int类型(既要看虚拟机内部的实现),即true用int 1 false用int 0表示 虚拟机内部没有boolean类型;
字节码:
iconst_1 压入int常量1
istore_2 存i
boolean[] i = new boolean[10]; //此时在堆上分配,数组元素在为byte类型
7: aload_1
8: iconst_0
9: iconst_1
10: bastore //bastore b代表byte
摘自 《Java虚拟机规范(Java SE 7)》
引用
2.3.4 boolean类型
虽然 Java 虚拟机定义了 boolean 这种数据类型,但是只对它提供了非常有限的支持。在
Java 虚拟机中没有任何供 boolean 值专用的字节码指令,在 Java 语言之中涉及到 boolean
类型值的运算,在编译之后都使用 Java 虚拟机中的 int 数据类型来代替。
Java 虚拟机直接支持 boolean 类型的数组,虚拟机的 newarray 指令可以创建这种数组。
boolean 的数组类型的访问与修改共用 byte 类型数组的 baload 和 bastore 指令①。
参考:2-----> http://stackoverflow.com/questions/1907318/java-boolean-primitive-type-size
Short answer: yes, boolean values are manipulated as 32-bit entities, but arrays of booleans use 1 byte per element.
Longer answer: the JVM uses a 32-bit stack cell, used to hold local variables, method arguments, and expression values. Primitives that are smaller than 1 cell are padded out, primitives larger than 32 bits (long and double) take 2 cells. This technique minimizes the number of opcodes, but does have some peculiar side-effects (such as the need to mask bytes). Primitives stored in arrays may use less than 32 bits, and there are different opcodes to load and store primitive values from an array. Boolean and byte values both use the baload and bastore opcodes, which implies that boolean arrays take 1 byte per element. As far as in-memory object layout goes, this is covered under the "private implementation" rules, it can be 1 bit, 1 byte, or as another poster noted, aligned to a 64-bit double-word boundary. Most likely, it takes the basic word size of the underlying hardware (32 or 64 bits).
As far as minimizing the amount of space that booleans use: it really isn't an issue for most applications. Stack frames (holding local variables and method arguments) aren't very large, and in the big scheme a discrete boolean in an object isn't that large either. If you have lots of objects with lots of booleans, then you can use bit-fields that are managed via your getters and setters. However, you'll pay a penalty in CPU time that is probably bigger than the penalty in memory.
|