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

Posted by tunnuz on Stack Overflow See other posts from Stack Overflow or by tunnuz
Published on 2010-05-17T08:17:58Z Indexed on 2010/05/17 8:30 UTC
Read the original article Hit count: 602

Filed under:
|
|
|

Hello, I started working with C# a few weeks ago and I'm now in a situation where I need to build up a "bit set" flag to handle different cases in an algorithm. I have thus two options:

    enum RelativePositioning
    {
        LEFT = 0,
        RIGHT = 1,
        BOTTOM  = 2,
        TOP = 3,
        FRONT = 4,
        BACK = 5
    }

    pos = ((eye.X < minCorner.X ? 1 : 0) << RelativePositioning.LEFT)
        + ((eye.X > maxCorner.X ? 1 : 0) << RelativePositioning.RIGHT)
        + ((eye.Y < minCorner.Y ? 1 : 0) << RelativePositioning.BOTTOM)
        + ((eye.Y > maxCorner.Y ? 1 : 0) << RelativePositioning.TOP)
        + ((eye.Z < minCorner.Z ? 1 : 0) << RelativePositioning.FRONT)
        + ((eye.Z > maxCorner.Z ? 1 : 0) << RelativePositioning.BACK);

Or:

    enum RelativePositioning
    {
        LEFT = 1,
        RIGHT = 2,
        BOTTOM  = 4,
        TOP = 8,
        FRONT = 16,
        BACK = 32
    }

    if (eye.X < minCorner.X) { pos += RelativePositioning.LEFT;   }
    if (eye.X > maxCorner.X) { pos += RelativePositioning.RIGHT;  }
    if (eye.Y < minCorner.Y) { pos += RelativePositioning.BOTTOM; }
    if (eye.Y > maxCorner.Y) { pos += RelativePositioning.TOP;    }
    if (eye.Z > maxCorner.Z) { pos += RelativePositioning.FRONT;  }
    if (eye.Z < minCorner.Z) { pos += RelativePositioning.BACK;   }

I could have used something as ((eye.X > maxCorner.X) << 1) but C# does not allow implicit casting from bool to int and the ternary operator was similar enough. My question now is: is there any performance improvement in using the first version over the second?

Thank you
Tommaso

© Stack Overflow or respective owner

Related posts about c#

Related posts about bitwise