Today I found great article in Polygonal.de blog about useful bitwise operations and attempted to determine how effective those “tricks” are in C# .NET.
Note:
- All test were performed 1000000000 times with same values of all variables
- Difference was calculated using [(Method1_Time/Method2_Time)*100%] equation
- >100% difference indicates that bitwise operation was faster
Absolute value of an integer
x = i + (i >> 31) ^ (i >> 31); versus x = Math.Abs(x); Basic method: 6.51467910027671 Bitwise method: 2.73749624603127 Difference: 238%
Note: This particular example only Works with 32 bit integers
Universal code would look like this: [i + (i >> INT_SIZE-1) ^ (i >> INT_SIZE-1]
Multiplication by any power of two
x = x * 256; versus x = x << 8; Basic method: 3.54274747209492 Bitwise method: 2.95297894006082 Difference: 120%
Division by any power of two
x = x / 256; versus x = x >> 8; Basic method: 3.05552884514652 Bitwise method: 3.53027912765449 Difference: 87%
To my surprise, bitwise multiplication was faster, while division was slower (almost the same amount).
Swapping integers without additional temporary variable
int a = x; x = y; y = a; versus x ^= y; y ^= x; x ^= y; Basic method: 4.45572132771064 Bitwise method: 4.04139101477981 Difference: 110%
My favorite bitwise operation, which I use quite often. Although it’s only 10% faster, but it doesn’t require creation of a new temporary integer, uses less memory therefore there’s no need calling .NET garbage collector at the end.
Increase/Decrease integer by one
x++; x--; versus x = -~x; x = ~-x; Basic method: 3.44019505272318 Bitwise method: 3.70579836264106 Difference: 93%
Both x++ and x– are very frequent operations, so no wonder that compilers use all their potential to optimize them as good as they can. There’s no point using bitwise operations here.
Flipping sign of an integer
x = -x; versus x = ~x + 1; Basic method: 3.07309755848858 Bitwise method: 3.05791937243421 Difference: 100%
Bitwise operation provides almost identical speed, so I don’t see why to complicate your code with bitwise analog of simple [x = -x] code.
Modulo operation with divisors of any power by two
x = x % 32; versus x = x & (32 - 1); Basic method: 2.65090814614707 Bitwise method: 3.55706940407231 Difference: 75%
The only bitwise operation that was a lot slower then simple [x % c] way.
Further reading:
• cmschill.net
• veneroida.com
• wikipedia.org
