Flags attribute and bitwise enums in C Sharp (C#) - Time & Space Complexity
When using flags and bitwise enums, we want to know how fast operations like checking or combining flags run.
We ask: How does the time to process flags grow as we add more flags?
Analyze the time complexity of the following code snippet.
[Flags]
enum Permissions
{
None = 0,
Read = 1,
Write = 2,
Execute = 4,
Delete = 8
}
Permissions userPerms = Permissions.Read | Permissions.Write;
bool canWrite = (userPerms & Permissions.Write) == Permissions.Write;
This code combines flags using bitwise OR and checks a flag using bitwise AND.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Bitwise AND and OR operations on integer values representing flags.
- How many times: Each operation runs once per check or combination, no loops involved.
Each flag is a bit in an integer. Checking or combining flags uses simple bit operations that take the same time no matter how many flags there are.
| Input Size (number of flags) | Approx. Operations |
|---|---|
| 4 | 1 bitwise operation |
| 10 | 1 bitwise operation |
| 32 | 1 bitwise operation |
Pattern observation: The time stays the same even if we add more flags because bitwise operations work on fixed-size integers.
Time Complexity: O(1)
This means checking or combining flags takes the same short time no matter how many flags exist.
[X] Wrong: "Checking multiple flags takes longer as we add more flags because we have to check each one separately."
[OK] Correct: Bitwise operations check all flags at once using a single operation, so time does not grow with more flags.
Understanding how bitwise flags work and their constant-time checks shows you know efficient ways to handle multiple options compactly.
"What if we stored flags in a list instead of bits? How would the time complexity change?"