Why use flags+bitmasks rather than a series of booleans?

Winston Fassett picture Winston Fassett · Sep 10, 2009 · Viewed 11.3k times · Source

Given a case where I have an object that may be in one or more true/false states, I've always been a little fuzzy on why programmers frequently use flags+bitmasks instead of just using several boolean values.

It's all over the .NET framework. Not sure if this is the best example, but the .NET framework has the following:

public enum AnchorStyles
{
    None = 0,
    Top = 1,
    Bottom = 2,
    Left = 4,
    Right = 8
}

So given an anchor style, we can use bitmasks to figure out which of the states are selected. However, it seems like you could accomplish the same thing with an AnchorStyle class/struct with bool properties defined for each possible value, or an array of individual enum values.

Of course the main reason for my question is that I'm wondering if I should follow a similar practice with my own code.

So, why use this approach?

  • Less memory consumption? (it doesn't seem like it would consume less than an array/struct of bools)
  • Better stack/heap performance than a struct or array?
  • Faster compare operations? Faster value addition/removal?
  • More convenient for the developer who wrote it?

Answer

gbjbaanb picture gbjbaanb · Sep 10, 2009

It was traditionally a way of reducing memory usage. So, yes, its quite obsolete in C# :-)

As a programming technique, it may be obsolete in today's systems, and you'd be quite alright to use an array of bools, but...

It is fast to compare values stored as a bitmask. Use the AND and OR logic operators and compare the resulting 2 ints.

It uses considerably less memory. Putting all 4 of your example values in a bitmask would use half a byte. Using an array of bools, most likely would use a few bytes for the array object plus a long word for each bool. If you have to store a million values, you'll see exactly why a bitmask version is superior.

It is easier to manage, you only have to deal with a single integer value, whereas an array of bools would store quite differently in, say a database.

And, because of the memory layout, much faster in every aspect than an array. It's nearly as fast as using a single 32-bit integer. We all know that is as fast as you can get for operations on data.