Jump to content
  • Advertisement
Sign in to follow this  

which is better to use as an event determinant, boolean or bit flags?(Java)

This topic is 5008 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Booleans has low memory usage. Using it is, I think, fast. As easy as if( someBoolean ) { ...perform stuff } or if( !someBoolean ) //a little overhead with the not(!) operator { ...do stuff } But if an application uses more flags, the app would have to create instances of more booleans which would increase memory usage. boolean isIntro, isGame, isPaused; boolean isWalk, isEncounter, isEvent; ... //more boolean With bitflags from an int (or byte), you'll only need one int. With its usage, more operators are needed though. I think it adds to the running time. if( ( flagInt & 1 ) != 0 ) { ...do stuff } But, bitflags are more flexible. An int bitflag could represent much more flags. That saves memory. So what do you say? I want to hear it. Correct me, comment me, suggest something.

Share this post

Link to post
Share on other sites
I think memory is not an issue in your case.
The VM is free to implement booleans as bitflags, but using booleans makes your code much cleaner.

Bitflags on the other hand provide a way to quickly check for a certain combination of flags:

boolean isTrue = (value & (FLAG1 | FLAG2)) == FLAG1;

The result is true if FLAG1 is set, but FLAG2 is not.

Share this post

Link to post
Share on other sites
Then you should take a look into the VM specification, and read the bytecode your compiler produced.

If you write

final static int FLAG1 = 4;
final static int FLAG2 = 8;

Then you will have an entry in your constant pool for each flag name. And I would not recommend hardcoding the constants in your code.

However using an int instead of a boolean may provide some savings in memory usage if there are many objects floating around. Testing, setting and clearing flags does cost more operations than working on a boolean.

So maybe what you need depends on the number of places where you check/modify those flags.

Perhaps writing a 'class BitSet' would be an option.

Another thing you may try is using a preprocessor (like CPP) in a first run over your code to replace things like

if( ( flagInt & 1 ) != 0 )


if ( TEST_FLAG(flagInt, 1) )

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!