SeraphimFoA
SeraphimFoA

Reputation: 466

C# Performance and best practice to check the state of a bit Array

Here's my problem:

My issue is to find a REALLY fast way of checking if an instance of ClassObj match a particular set of ClassProperty (if he have in his lstProperty all the ClassProperty of a given set).

I was thinking about creating an array of Bit representing the sequence of ClassProperty that the ClassObj posesses. Using as reference the Array arrPossibleProperty, and the index of his Property.

So if for example we have 10 property and a InstanceA of ClassObj have the 1st the 4th and the 9th I would generate this array of bit: 1001000010

My question is, how can I check for example (Fastest and Most performing solution) that the array of bit have (for example) the 3rd and the 4th Property?

Of course if you need there's a more performing way of doing this let me know.

Upvotes: 0

Views: 392

Answers (2)

Nilzor
Nilzor

Reputation: 18593

You say your array of all possible ClassProperty-objects (arrPossibleProperty) are initalized at run-time. I then assume you don't know how large that array might be. That rules out Enums, which by definition are hard coded. If you instead go for some sort of bitmap as you indicate in your question, you need at some point to iterate arrPossibleProperty and your list of ClassProperty lstProperty in order to do the mapping and unmapping.

My point is you are making a lot of assumptions claiming that doing this bit-fiddling is faster, while you're actually working with high-level C# objects. Never assume. Test. Measure.

Here is a question quite similar to yours, in which the answer uses standard .NET library functions to do what you want:

HashSet<T>().IsSupertSetOf().

Is it fast enough? Then use it instead of creating far more unreadable code with bit-operations.

Upvotes: 1

Nolonar
Nolonar

Reputation: 6132

You'll want to use bitwise-operations, such as &, |, ^ or ~ (depending on your needs)

Taking your example of 1001000010, to find out if the 3rd bit is set, you'd want to do this: 1001000010 & 0000000100 != 0000000000, or rather

bool isSet = myProperty & (1 << (option - 1)) != 0; // to find out if `myProperty` has the property `option` set.
myProperty |= 1 << (option -  1); // to set property `option`

For more information about bitwise operations: http://en.wikipedia.org/wiki/Bitwise_operation

Alternatively and a lot more easy to implement, would be using enums.

[Flags]
enum ClassProperty
{
    None = 0x00,
    First = 0x01,
    Second = 0x02,
    Third = 0x04,
    Fourth = 0x08
    // add more if needed
}

Then, you'd use the enum like this

myProperty = ClassProperty.First | ClassProperty.Second; // sets both First and Second
bool thirdIsSet = myProperty.HasFlag(ClassProperty.Third);

Upvotes: 1

Related Questions