boolean到底占几个字节

boolean是4字节,boolean数组是1字节

1. 代码

https://stackoverflow.com/questions/383551/what-is-the-size-of-a-boolean-variable-in-java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
class LotsOfBooleans{
boolean a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, aa, ab, ac, ad, ae, af;
boolean b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bb, bc, bd, be, bf;
boolean c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, ca, cb, cc, cd, ce, cf;
boolean d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, da, db, dc, dd, de, df;
boolean e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, ea, eb, ec, ed, ee, ef;
}
class LotsOfInts{
int a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, aa, ab, ac, ad, ae, af;
int b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bb, bc, bd, be, bf;
int c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, ca, cb, cc, cd, ce, cf;
int d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, da, db, dc, dd, de, df;
int e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, ea, eb, ec, ed, ee, ef;
}

public class test {

private static final int SIZE = 100000;

public static void main(String[] args) throws Exception {

LotsOfBooleans[] first = new LotsOfBooleans[SIZE];
LotsOfInts[] second = new LotsOfInts[SIZE];

//clean
System.gc();
long startMem = getMemory();

for (int i=0; i < SIZE; i++) {
first[i] = new LotsOfBooleans();
}

System.gc();
long endMem = getMemory();

System.out.println ("Size for LotsOfBooleans: " + (endMem-startMem));
System.out.println ("Average size: " + ((endMem-startMem) / ((double)SIZE)));

System.gc();
startMem = getMemory();

for (int i=0; i < SIZE; i++) {
second[i] = new LotsOfInts();
}

System.gc();
endMem = getMemory();

System.out.println ("Size for LotsOfInts: " + (endMem-startMem));
System.out.println ("Average size: " + ((endMem-startMem) / ((double)SIZE)));

// Make sure nothing gets collected
long total = 0;
for (int i=0; i < SIZE; i++) {
total += (first[i].a0 ? 1 : 0) + second[i].a0;
}
System.out.println(total);
}
private static long getMemory() {
Runtime runtime = Runtime.getRuntime();
return runtime.totalMemory() - runtime.freeMemory();
}
}

/**
Size for LotsOfBooleans: 9092960
Average size: 90.9296
Size for LotsOfInts: 33599984
Average size: 335.99984
0
*/

2. 分析

结果int数组是boolean数组的4倍左右,int是4字节,boolean数组应是1字节

<<Java虚拟机规范>>:

  • 在Java虚拟机中没有任何供 boolean值专用的字节码指令,Java语言表达式所操作的
    boolean值,在编译之后都使用Java虚拟机中的int数据类型来代替。

    int是4字节,boolean就是4字节

  • Java虚拟机直接支持 boolean类型的数组,虚拟机的 navarra指令可以创建这种数组。boolean类型数组的访问与修改共用byte类型数组的baload和 bastore指令

    两者字节相同时才能通用,byte是1字节,boolean数组也是1字节

but It depends on the virtual machine,上述只是规范,具体还是看虚拟机实现

本文结束  感谢您的阅读