无符号与有符号整数的性能 [英] performance of unsigned vs signed integers

查看:33
本文介绍了无符号与有符号整数的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用无符号整数而不是有符号整数是否有任何性能增益/损失?

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

这篇关于无符号与有符号整数的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆