-
Bitwise Alternatives to Multiply, Divide, and Modulus: Faster?
Many programmers are aware of a special case where you can use a bitwise shift for multiplication or division when you’re multiplying or dividing by a power of two. For example, you can replace
i * 2
withi << 1
andi / 2
withi >> 1
. A lesser-known trick works for modulus. But are these alternatives actually any faster? Today's article puts them to the test!Here are today's competitors:
Here's a performance test that performs each of these operations a lot of times:
I ran this test app in the following environment:
- Flex SDK (MXMLC) 4.6.0.23201, compiling in release mode (no debugging or verbose stack traces)
- Release version of Flash Player 11.3.300.271
- 2.3 Ghz Intel Core i7
- Mac OS X 10.8.0
And here are the results I got:
Method Time Div: i / 4 358 Div: i >> 2 224 Mul: i * 4 206 Mul: i << 2 255 Mod: i % 4 918 Mod: i & 3 254 The above results validate the bitwise versions in two out of three tests: division and modulus. In the multiplication case, the normal version actually performs about 20% faster than the bitwise equivalent. On the other hand, division is nearly twice as fast with the bitwise shift and the bitwise modulus (really just an
&
) is more than three times faster! So if you're got a lot of divides or mods in your performance-critical code, swap them over to the bitwise versions!
- 1) How does mod of power of 2 work on only lower order bits of a binary number (1011000111011010) ?
- 2) What is this number mod 2 to power 0, 2 to power 4 ?
- 3) What does power of 2 have to do with the modulo operator ? Does it hold a special property ?
- 4) Can someone give me an example ?
The instructor says "When you take something mod to power of 2 you just take its lower order bits". I was too afraid to ask what he meant =)