#1,114 – Don’t Use Shift Operators to Do Multiplication

When you use the shift operators on integer-based values, you effectively multiply a number by two when you do a left shift by one bit and divide a number by two when you do a right shift by one bit.

In years past, you’d sometimes hear a recommendation that you should prefer using the shift operators over multiplicative operators because the shift operators were faster.

With modern optimizing compilers, you should no longer worry about this level of optimization and performance.  If you need to multiply a number by a power of two, you should express your intent by using the multiplicative operators.  (E.g. “* 2” or “* 4”).  The compiler will figure out that fastest way to accomplish this.

Advertisements