无符号与有符号整数的性能
使用无符号整数而不是有符号整数是否有任何性能增益/损失?
Is there any performance gain/loss by using unsigned integers over signed integers?
如果是这样,这是否也适用于短期和长期?
If so, does this goes for short and long as well?
推荐答案
使用 unsigned int
除以 2 的幂更快,因为它可以优化为单个移位指令.对于 signed int
,它通常需要更多的机器指令,因为除法 向零舍入,但向右移动 向下.示例:
Division by powers of 2 is faster with unsigned int
, because it can be optimized into a single shift instruction. With signed int
, it usually requires more machine instructions, because division rounds towards zero, but shifting to the right rounds down. Example:
int foo(int x, unsigned y)
{
x /= 8;
y /= 8;
return x + y;
}
这里是相关的 x
部分(签名除法):
Here is the relevant x
part (signed division):
movl 8(%ebp), %eax
leal 7(%eax), %edx
testl %eax, %eax
cmovs %edx, %eax
sarl $3, %eax
这里是相关的 y
部分(无符号除法):
And here is the relevant y
part (unsigned division):
movl 12(%ebp), %edx
shrl $3, %edx
相关文章