Which is faster: x<<1 or x<<10?

前端 未结 9 2084
感情败类
感情败类 2020-12-13 03:32

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.

9条回答
  •  感动是毒
    2020-12-13 04:06

    It is conceivable that, on an 8-bit processor, x<<1 could actually be much slower than x<<10 for a 16-bit value.

    For example a reasonable translation of x<<1 may be:

    byte1 = (byte1 << 1) | (byte2 >> 7)
    byte2 = (byte2 << 1)
    

    whereas x<<10 would be more simple:

    byte1 = (byte2 << 2)
    byte2 = 0
    

    Notice how x<<1 shifts more often and even farther than x<<10. Furthermore the result of x<<10 doesn't depend on the content of byte1. This could speed up the operation additionally.

提交回复
热议问题