Any significant performance improvement using bitwise operators instead of simple int sums in C #?

I started working with C # a few weeks ago, and now I'm in a situation where I need to create a bit-bit flag to handle various cases in the algorithm. I have two options:

enum RelativePositioning { LEFT = 0, RIGHT = 1, BOTTOM = 2, TOP = 3, FRONT = 4, BACK = 5 } pos = ((eye.X < minCorner.X ? 1 : 0) << (int) RelativePositioning.LEFT) + ((eye.X > maxCorner.X ? 1 : 0) << (int) RelativePositioning.RIGHT) + ((eye.Y < minCorner.Y ? 1 : 0) << (int) RelativePositioning.BOTTOM) + ((eye.Y > maxCorner.Y ? 1 : 0) << (int) RelativePositioning.TOP) + ((eye.Z < minCorner.Z ? 1 : 0) << (int) RelativePositioning.FRONT) + ((eye.Z > maxCorner.Z ? 1 : 0) << (int) RelativePositioning.BACK); 

Or:

  enum RelativePositioning { LEFT = 1, RIGHT = 2, BOTTOM = 4, TOP = 8, FRONT = 16, BACK = 32 } if (eye.X < minCorner.X) { pos += (int) RelativePositioning.LEFT; } if (eye.X > maxCorner.X) { pos += (int) RelativePositioning.RIGHT; } if (eye.Y < minCorner.Y) { pos += (int) RelativePositioning.BOTTOM; } if (eye.Y > maxCorner.Y) { pos += (int) RelativePositioning.TOP; } if (eye.Z > maxCorner.Z) { pos += (int) RelativePositioning.FRONT; } if (eye.Z < minCorner.Z) { pos += (int) RelativePositioning.BACK; } 

I could use something like ((eye.X > maxCorner.X) << 1) , but C # does not allow implicit casting from bool to int, and the ternary operator was pretty similar. Now my question is: is there a performance improvement when using the first version for the second?

Thanks,
Tommaso

+7
performance c # bit-manipulation int
source share
3 answers

The inline if ( ? , : Operator will generate almost the same IL as the standard if list in the second example. The only difference you'll see here is the specific operations that the processor will perform, and I can argue that ADD faster than SHL .
Since you are going to add the results anyway, I would choose the second example (plus this makes reading easier).

EDIT
I just checked the IL of both examples, and this contradicts what I said above.
The first example generates a lot less IL (34 lines less), so you will need to run a performance test to really determine if it is faster.

+5
source share

You must definitely use the Flags attribute for your listing. So it will look something like this:

 [Flags] public enum RelativePositionings { None = 0, Left = 1, Right = 2, Bottom = 4, Top = 8, Front = 16, Back = 32 } 

With this, you can do things like:

 var position = RelativePositionings.Left | RelativePositionings.Front; 

and check for each state:

 if(position.HasFlag(RelativePositioning.Left)) { //To do: if left bit is set? } 
+8
source share

Significantly faster? not. A little faster? Little.

0
source share

All Articles