布尔变量 java_Java中布尔变量的大小是多少?

这篇博客探讨了在Java中布尔值和整型数据在内存占用上的差异。通过创建大量布尔值和整型数组并测量内存变化,结果显示Sun的JVM将布尔值有效地打包到了一个字节,而每个整型则占用更多内存。实验在JDK 1.6.0_11的Windows环境下进行。
摘要由CSDN通过智能技术生成

它取决于虚拟机,但很容易从类似的问题调整代码,询问Java中的字节:

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 = 1000000;

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

{

LotsOfBooleans[] first = new LotsOfBooleans[SIZE];

LotsOfInts[] second = new LotsOfInts[SIZE];

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();

}

}

重申一下,这是依赖于VM的,但是在运行Sun的JDK build 1.6.0_11的Windows笔记本电脑上,我得到了以下结果:

Size for LotsOfBooleans: 87978576

Average size: 87.978576

Size for LotsOfInts: 328000000

Average size: 328.0

这表明布尔值基本上可以由Sun的JVM打包成一个字节。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值