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

Started by
2 comments, last by nmi 19 years, 4 months ago
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.
Advertisement
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.
Memory and efficiency is an issue. I'm doing J2ME.
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 )

by

if ( TEST_FLAG(flagInt, 1) )

This topic is closed to new replies.

Advertisement