Is there any performance gain/loss by using unsigned integers over signed integers?
If so, does this goes for short and long as well?
In C, why is signed int faster than unsigned int ? True, I know that this has been asked and answered multiple times on this website (links below). However, most people said that there is no difference. I have written code and accidentally found a significant performance difference.
Unsigned integers are used when we know that the value that we are storing will always be non-negative (zero or positive). Note: it is almost always the case that you could use a regular integer variable in place of an unsigned integer.
When no negative numbers are required, unsigned integers are well-suited for networking and systems with little memory, because unsigned integers can store more positive numbers without taking up extra memory. New programmers sometimes get signed and unsigned mixed up.
If Data is signed type negative value, the right shifting operation of Data is implementation-dependent but for the unsigned type, it would be Data/ 2pos. If Data is signed type negative value, the left shifting operation of Data shows the undefined behavior but for the unsigned type, it would be Data x 2pos.
On most processors, there are instructions for both signed and unsigned arithmetic, so the difference between using signed and unsigned integers comes down to which one the compiler uses. If any of the two is faster, it's completely processor specific, and most likely the difference is miniscule, if it exists at all.
In C++ (and C), signed integer overflow is undefined, whereas unsigned integer overflow is defined to wrap around. Notice that e.g. in gcc, you can use the -fwrapv flag to make signed overflow defined (to wrap around).
Signed integer operations can be more expensive on nearly all architectures. For example, division by a constant is faster when unsigned, e.g: But... Same goes for modulo. This also holds true for non-powers-of-2 (but the example is more complex).
Because signed integer overflow is undefined, the compiler can make a lot of assumptions and optimizations on code involving signed integers. Unsigned integer overflow is defined to wrap around, so the compiler won't be able to optimize as much.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With