问题描述
Java虚拟机规范说对布尔原始类型的支持有限。
The Java Virtual Machine Specification says that there is limited support for boolean primitive types.
以上暗示(虽然我可能误解了它)在操作布尔值时使用int数据类型,但这是一个32位内存构造。鉴于布尔值仅代表1位信息:
The above implies (although I may have misinterpreted it) that the int data type is used when operating on booleans, but this is a 32 bit memory construct. Given that a boolean only represents 1 bit of information:
- 为什么字节或短字型不用作布尔值的代理而不是int?
- 对于任何给定的JVM,最准确地找出用于存储布尔类型的内存的最可靠方法是什么?
推荐答案
简答:是的,布尔值被操作为32位实体,但数组布尔值使用每个元素1个字节。
Short answer: yes, boolean values are manipulated as 32-bit entities, but arrays of booleans use 1 byte per element.
更长的答案:JVM使用32位堆栈单元,用于保存局部变量,方法参数和表达式值。填充小于1个单元的基元,大于32位(长和双)的基元需要2个单元。这种技术最大限度地减少了操作码的数量,但确实有一些特殊的副作用(例如需要屏蔽字节)。
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).
存储在数组中的基元可能使用少于32个位,并且有不同的操作码来加载和存储来自数组的原始值。布尔值和字节值都使用baload和bastore操作码,这意味着布尔数组每个元素占用1个字节。
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.
就内存中对象布局而言,这是私人实施下的规则,它可以是1位,1个字节,或者作为另一个海报记录,与64位双字边界对齐。最有可能的是,它需要底层硬件的基本字大小(32或64位)。
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).
尽量减少布尔使用的空间量:对于大多数应用程序来说,它确实不是问题。堆栈帧(保存局部变量和方法参数)不是很大,并且在大方案中,对象中的离散布尔值也不是那么大。如果你有很多带有大量布尔值的对象,那么你可以使用通过你的getter和setter来管理的位域。但是,您将在CPU时间内支付一个可能大于内存惩罚的惩罚。
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.
这篇关于为什么没有定义Java的布尔基元大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!