Why is Java's boolean primitive size not defin

2019-01-01 14:40发布

The Java Virtual Machine Specification says that there is limited support for boolean primitive types.

There are no Java virtual machine instructions solely dedicated to operations on boolean values. Instead, expressions in the Java programming language that operate on boolean values are compiled to use values of the Java virtual machine int data type.

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:

  • Why is a byte, or short, type not used as the proxy for a boolean instead of int?
  • For any given JVM what's the most reliable way of finding out exactly how much memory is used to store a boolean type?

标签: java boolean
7条回答
孤独寂梦人
2楼-- · 2019-01-01 15:31

The boolean mapping was done with a 32bit CPU in mind. The int value has 32 bits so it can be processed in one operation.

Here's a solution from Peter Norvig's Java IAQ: Infrequently Answered Questions to measure the size (with some imprecision):

static Runtime runtime = Runtime.getRuntime();
...
long start, end;
Object obj;
runtime.gc();
start = runtime.freememory();
obj = new Object(); // Or whatever you want to look at
end =  runtime.freememory();
System.out.println("That took " + (start-end) + " bytes.");
查看更多
登录 后发表回答