-
Speed of 'unsigned int'
Hi
I have read that arithmetic operations using unsigned int are faster that int, so I wrote my program to use them where I could. The problem is that I need a few signed int vars, and those vars make arithmetics operations with the unsigned int vars, so a cast is doing.
My questions is:
is it better for speed to have signed and unsigned int vars and use them together or would be better to only have signed int, so that no cast is done?
thx in advance
-
I think that you are being a little penny wise pound foolish to worry about this. Profile your code and see if these computations constitute a bottle neck. If they do, create two versions of the same code, one using ints and the other using unsigned int with casting, then time and compare the difference.
-
This will obviously depend a little bit on the processor architecture, but my summary below holds for ALMOST all processors.
For most intents and purposes, it probably makes no difference. Mixing signed with unsigned MAY introduce extra "sign-extend" instructions if you also have types of different size (e.g. short, char mixed with int/long). In old times (around 486 days), the sign extend or extend with zero instructions where slightly slower than the plain move instructions, but on modern processors any register to register move with or without extension will be a single cycle (and can usually be performed in parallel with other instructions, so it's likely that it causes no effect at all on the code's execution time).
Other than when changing the size of the value, the only difference between signed and unsigned is that the compiler chooses different condition codes for comparisons (that is, it chooses "jump above" for unsigned or "jump greater than" for a signed comparison, which will have no effect on the execution speed at all - the jump instruction takes the same time whether it is the signed variant or the unsigned variant.
--
Mats