關於Java中的boolean類型所佔存儲空間

http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/java/nutsandbolts/datatypes.html
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.

總是有人爭論。確實一個bit可以表明,但是要看其工作原理,如果其工作是按字節處理數據,顯然boolean被定義爲一個bit會使得處理比較麻煩,因而不妥。
而我看到的中文論壇中頂多討論到boolean是可以用1個bit表明,但不是被精確定義的到此爲止。
但是作爲一個要實現的內容,必須要有明確的定義,而這個定義是在JVM或是其他地方?
據搜,定義是在JVM
http://stackoverflow.com/questions/383551/what-is-the-size-of-a-boolean-variable-in-java
這帖有人給出了測量所佔mem的程序例子
That suggests that booleans can basically be packed into a byte each by Sun's JVM.

http://www.velocityreviews.com/forums/t364574-size-of-boolean-type.html#6

It is up to the individual JVM implementation. It is possible that
different amounts of memory will be allocated in different situations.
However, the case that is both most interesting and most measurable is a
large boolean[] array.

I've previously measured it as one byte per element, rounded up to a
multiple of 8 and plus 8 bytes per array overhead. However, your mileage
may vary, and if you really need to know you should measure it on the
system you care about.

Patricia

http://www.daniweb.com/forums/thread33136.html#2
There is no need to know. A boolean is a boolean is a boolean. How it's defined internally is inconsequential to the person using the datatype.
It could even be different on different JVMs, so counting on a particular implementation is dangerous.
這位則說,內部如何定義不重要,刻意計算其佔容反而會因爲在不同JVM中定義不同而變得不安全。

http://forums.sun.com/thread.jspa?threadID=5434070 SIZE of Boolean

打開sun的JVM庫的boolean,也看不懂也看不出哪裏有寫了佔有多少內存。


原文地址:http://hi.baidu.com/redareyou/blog/item/649fb9119cc0dfcba7ef3f1b.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章