Flexo Flexo - 1 year ago 113
C Question

performance of unsigned vs signed integers

Is there any performance gain/loss by using unsigned integers over signed integers?

If so, does this goes for short and long as well?

Answer Source

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;

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

And here is the relevant y part (unsigned division):

movl 12(%ebp), %edx
shrl $3, %edx
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download