Reputation: 5162
Is using boolean
instead of byte
(if I need 2 states) in Java useful for performance or it's just illusion... Does all the space profit leveled by alignment?
Upvotes: 0
Views: 1622
Reputation: 533920
Only most JVMs a boolean uses the same amount of space as a byte. Accessing a byte/boolean can be more work than accessing an int or long, so if performance is the only consideration, a int or long can be faster. When you share a value between threads, there can be an advantage to reserving a whole cache line to the field (in the most extreme cases) This is 64-bytes on many CPUs.
Upvotes: 1
Reputation: 2571
If you only have 2 states that you want to represent, and you want to reduce memory usage you can use a java.util.BitSet
.
Upvotes: 1
Reputation: 40707
To give you an idea, I once consulted in a mini-shop (16-bit machines).
Sometimes people would have a "flag word", a global int containing space for 16 boolean flags.
This was to save space.
Never mind that to test a flag required two 16-bit instructions, and to set a flag required three or more.
Upvotes: 2
Reputation: 13097
You should use whichever is clearer, unless you have profiled your code, and decided that making this optimization is worth the cost in readability. Most of the time, this sort of micro-optimization isn't worth the performance increase.
According to Oracle,
boolean: ... This data type represents one bit of information, but its "size" isn't something that's precisely defined.
Upvotes: 4
Reputation: 500953
The answer depends on your JVM, and on your code. The only way to find out for sure is by profiling your actual code.
Upvotes: 1
Reputation: 8582
Yes, boolean may use only 1 bit. But more important, it makes it clearer for another developer reading your code that there are only two possible states.
Upvotes: 1