I don\'t want to optimize anything, I swear, I just want to ask this question out of curiosity. I know that on most hardware there\'s an assembly command of bit-shift (e.g.
There are many cases on this.
Many hi-speed MPUs have barrel shifter, multiplexer-like electronic circuit which do any shift in constant time.
If MPU have only 1 bit shift x << 10
would normally be slower, as it mostly done by 10 shifts or byte copying with 2 shifts.
But there is known common case where x << 10
would be even faster than x << 1
. If x is 16 bit, only lower 6 bits of it is care (all other will be shifted out), so MPU need to load only lower byte, thus make only single access cycle to 8-bit memory, while x << 10
need two access cycles. If access cycle is slower than shift (and clear lower byte), x << 10
will be faster. This may apply to microcontrollers with fast onboard program ROM while accessing slow external data RAM.
As addition to case 3, compiler may care about number of significant bits in x << 10
and optimize further operations to lower-width ones, like replacing 16x16 multiplication with 16x8 one (as lower byte is always zero).
Note, some microcontrollers have no shift-left instruction at all, they use add x,x
instead.