Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a boolean array take more space than a number of the same size?

Would a boolean array of size 32 take more space than an integer variable, for example? If so, then why and by how much?

CLARIFICATION:

In java (if that is relevant, forgive me - I am not sure). Would this line:

boolean arr=new boolean[32];

take more space than this line:

int num;
like image 318
user2705335 Avatar asked Aug 25 '13 13:08

user2705335


1 Answers

An array of 32 booleans in Java takes about eight times the space of a Java int. This is because in most computer architectures the smallest addressable unit of memory is an eight-bit byte, so making an array of "packed" booleans requires additional overhead.

If you would like to use one bit per boolean, use BitSet class instead of an array of booleans. Note that you would get some overhead in addition to the data itself, so using such data structures for only 32 bits may not be economical enough to justify switching away from a simple array.

like image 154
Sergey Kalinichenko Avatar answered Nov 17 '22 11:11

Sergey Kalinichenko