I'm trying to get basic skills in working with bits using C#.NET. I posted an example yesterday with a simple problem that needs bit manipulation which led me to the fact that there are two main approaches - using bitwise operators
or using .NET abstractions such as BitArray
(Please let me know if there are more build-in tools for working with bits other than BitArray
in .NET and how to find more info for them if there are?).
I understand that bitwise operators
work faster but using BitArray
is something much more easier for me, but one thing I really try to avoid is learning bad practices. Even though my personal preferences are for the .NET abstraction(s) I want to know which i actually better to learn and use in a real program. Thinking about it I'm tempted to think that .NET abstractions are not that bad at, after all there must be reason to be there and maybe being a beginner it's more natural to learn the abstraction and later on improve my skills with low level operations, but this is just random thoughts.
It really depends on what you are doing with it. I'd say use bitwise operations when speed is more of a concern as they have much less overhead. Otherwise, BitArray's should be fine. The main overhead associated is function calls and some limits on "tricks" you can do.
For instance, if you wanted to do something if bits 0, 3, or 4 where set in a value:
if((value & 0b11001)>0) //not sure this is valid syntax, but you get the idea
{
//do stuff
}
Which because integers are a native CLR type, translates almost directly to just 3 native opcodes, mov
, and
, and cmp
where as for a BitArray, the most effecient way I see is this:
if(value[0] || value[3] || value[4])
{
//...
}
Where (assuming not JIT), this equals up to 3 function calls of light complexity. The simplest way to get a bit value from the backing integer(I assume) of a BitArray looks like this:
bool GetBit(int which)
{
return value & (1 << which)>0;
}
This basically means it equates to being about 2 times slower for just one bit For this super simple case, this would mean about 6 times slower since we are checking 3 bits.
And also for BitArrays, copies may be more expensive, as they aren't a native CLR type. I'd suspect this overhead is JITed away for the most part, but still something to consider, especially if targetting a compact framework.
Basically, only use BitArrays if you're not ever going to need to do complex bitwise operations on them.
Note: you can also use a hybrid approach of converting between integers and BitArrays, but this can have quite a bit of overhead as well.