Note that there are some explanatory texts on larger screens.

plurals
  1. POIs byte more efficient than boolean[8]
    primarykey
    data
    text
    <p>If I need 8 boolean member variables in a class, does Java effectively place them all in one byte? Or will it use a byte for each? In other words, is the memory footprint different for:</p> <pre><code>boolean a; boolean b; boolean c; boolean d; boolean e; boolean f; boolean g; boolean h; </code></pre> <p>vs.</p> <pre><code>public static final int a = 0x01; public static final int b = 0x02; public static final int c = 0x04; public static final int d = 0x08; public static final int e = 0x10; public static final int f = 0x20; public static final int g = 0x40; public static final int h = 0x80; byte flags; </code></pre> <p>I'm asking because I will be instantiating a <strong>lot</strong> of these objects. So having it take 1 byte instead of 8 bytes of memory will be a noticeable savings.</p> <p><strong>Update:</strong> This is definitely similar to the linked questions that list that a boolean is stored in an int (thank you for those links and sorry I didn't find them before asking). This question is a little different in that it presents the specific alternative of using a byte and bit flags. I don't know if this is sufficient to make this question not a duplicate.</p> <p><strong>Update 2:</strong> I just ran this using <a href="https://code.google.com/p/core-java-performance-examples/source/browse/trunk/src/main/java/com/google/code/java/core/sizeof/SizeofUtil.java" rel="nofollow">SizeofUtil</a> and found the following. The 8 booleans requires 24 bytes/object or 3 bytes/boolean. The single byte approach requires 10 bytes/object. I would understand 8 where it's expanding a byte to a native int (I'm on a 64-bit system). But what's with the other 2 bytes?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload