When is it better to store flags as a bitmask rather than using an associative table?

Splendid question!

Firstly, let’s make some assumptions about “better”.

I’m assuming you don’t much care about disk space – a bitmask is efficient from a space point of view, but I’m not sure that matters much if you’re using SQL server.

I’m assuming you do care about speed. A bitmask can be very fast when using calculations – but you won’t be able to use an index when querying the bitmask. This shouldn’t matter all that much, but if you want to know which users have create access, your query would be something like

select * from user where permsission & CREATE = TRUE

(haven’t got access to SQL Server today, on the road). That query would not be able to use an index because of the mathematical operation – so if you have a huge number of users, this would be quite painful.

I’m assuming you care about maintainability. From a maintainability point of view, the bitmask is not as expressive as the underlying problem domain as storing explicit permissions. You’d almost certainly have to synchronize the value of the bitmask flags across multiple components – including the database. Not impossible, but pain in the backside.

So, unless there’s another way of assessing “better”, I’d say the bitmask route is not as good as storing the permissions in a normalized database structure. I don’t agree that it would be “slower because you have to do a join” – unless you have a totally dysfunctional database, you won’t be able to measure this (whereas querying without the benefit of an active index can become noticably slower with even a few thousand records).

Leave a Comment