Here's a stupid scenario to illustrate a problemLet's say that sometimes some boolean variable "condition" is trueNow, we have some object, and one of this object's "jobs" is to make condition false is condition is ever true.

Is there a point to doing

1 2 3

if(condition){condition = false;}

or is simply doing

1

condition = false;

faster? (does it change, depending on about how often "condition" is true?)

Does looking up the state of a variable take less time than simply setting it?This is just a miniscule efficiency problem that i've always wondered about.

RELATED: do certain "lookups" take longer than others? Like, does checking a boolean take less time than checking an int, and does that take less time than checking if an object is some subclass? By how much?

Booleans are not represented by one bit by the JVM - if I recall correctly a boolean value might take up to 4 bytes of memory. I think checking for true and then setting to false cannot ever be faster - you have to read the value, make a comparison then write the value. I think there might be something wrong with the flow if you are setting the field a zillion times...

Are we talking about the same boolean here? Do you actually mean the java.lang.Boolean (which of course can get 32 bytes big... all the JVM overhead :O ) or are we talking about the generic-type-boolean, which (I'm pretty sure) takes 1 byte ?

Good find!And now i also know that using an array of booleans is less efficient than using N booleans

Nope... Looks like booleans inside the STACK are 32 bits of data. But inside Arrays and classes they only take 8 bits (as I expected). That is rather "normal", because C and some other languages also use 8 bits per boolean. In C++ there is the nice vector class, which has a implementation of boolean arrays taking only 1 bit per boolean. Access and writing is a bit slower, but I think thats quite okey for 8x less data

java-gaming.org is not responsible for the content posted by its members, including references to external websites,
and other references that may or may not have a relation with our primarily
gaming and game production oriented community.
inquiries and complaints can be sent via email to the info‑account of the
company managing the website of java‑gaming.org