Possible Duplicates:
Is shifting bits faster than multiplying and dividing in Java? .NET?
Quick Java Optimization Question
Many years ago in college, I learned that bit-shifting right by one accomplishes the same thing as dividing by two, but is generally significantly faster. I'm not sure how Java has come along in that regards since the 9-10 years ago I learned about that. Does the Java compiler automatically converts a divide-by-two into a bit-shift operation, or should I manually perform the bit-shift operation in the code myself?
When shifting right with a logical right shift, the least-significant bit is lost and a 0 is inserted on the other end. For positive numbers, a single logical right shift divides a number by 2, throwing out any remainders.
Bitshifting shifts the binary representation of each pixel to the left or to the right by a pre-defined number of positions. Shifting a binary number by one bit is equivalent to multiplying (when shifting to the left) or dividing (when shifting to the right) the number by 2.
So Yes, depending on the machine type, bitshift operators are faster than multiplication / division.
Division. To divide a number, a binary shift moves all the digits in the binary number along to the right and fills the gaps after the shift with 0: to divide by two, all digits shift one place to the right. to divide by four, all digits shift two places to the right.
Unless you're working in a shop and a codebase where bit-shifting is common then, IMHO, you're risking obfuscation. Yes, the expressions may be logically equivalent but:
All this is relative and, again, really depends on your shop's standards. If your colleagues love to bit-shift, then by all means go forth and bit-shift.
Yes, this is the very first thing that anyone attempting to do compiler optimizations will do (and has done for at least 5 decades), it most certainly is done by the Java JIT compiler, and you'd probably have a very hard time finding any compiler that doesn't do it.
And even if they didn't, it would still be a premature micro-optimization that should be avoided in favor of having the code be clearer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With