本文首发于微信公众号:程序员乔戈里
什么是boolean类型,根据:
boolean: the boolean data type has only two possible values: true and false. use this data type for simple flags that track true/false conditions. this data type represents one bit of information, but its "size" isn't something that's precisely defined.
谷歌翻译一下:
布尔类型:布尔数据类型只有两个可能的值:真和假。使用此数据类型为跟踪真/假条件的简单标记。这种数据类型就表示这一点信息,但是它的“大小”并不是精确定义
stackoverflow就有关于boolean占几个字节的讨论。
其中有一个高赞回答:
/** *出自公众号:程序员乔戈里 */ 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]; 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: 8257544 average size: 82.57544 size for lotsofints: 33599984 average size: 335.99984
java虚拟机规范一书提到 :
java规范中,没有明确指出boolean的大小。在《java虚拟机规范》给出了单个boolean占4个字节,和boolean数组1个字节的定义,具体 还要看虚拟机实现是否按照规范来,
references:
[1] 官方文档的描述:
[2] what-is-the-size-of-a-boolean-variable-in-java:
[3] 所以1个字节、4个字节都是有可能的:
如果是头条用户,可以在我的头条号程序员乔戈里后台回复 资源获取价值59998元的编程和考研资料
觉得文章不错的欢迎关注我的wx公众号:程序员乔戈里
我是bat大厂后台开发工程师,,专注分享技术干货/编程资源/求职面试/成长感悟等,关注送5000g编程资源和自己整理的一份帮助不少人拿下java的offer的面经附答案,免费下载csdn资源。
如对本文有疑问, 点击进行留言回复!!
springcloud中feign调用处理mybatis-plus Ipage反序列化问题。
Flume 史上最全面的大数据学习第十篇(一) 别再说不知道flume是什么了
网友评论