Posts

Es werden Posts vom Oktober, 2016 angezeigt.

The Power of Bit Shifts

I have noticed that you can gain huge speed optimization by doing calculations involving powers of two in a clever way.

Originally I had several passages like this in my code:

for (int j = 0; j < n; j++) i |= Math.Pow(2, j);

When I replaced the generic Math.Pow call with a call to a new method, I already gained a lot of speed.

private static ulong Math_Pow2(int j) { return (ulong)1 << j; }

But that was not all I was able to do. I gained yet more speed by doing the loop this way:

for (int j = n, ulong Math_Pow2_j = 1; j > 0; j--, Math_Pow2_j <<= 1) i |= Math_Pow2_j;

From originally 5 minutes, I managed to improve the run-time of a calculation to less than 30 seconds.

Bit shifts can help getting your code a lot faster.