I stumbled upon this piece of code in .NET\'s List source code:
// Following trick can reduce the range check by one
if ((uint) index >= (uint)_size) {
While exploring this on an intel processor I found no differene in execution times, possibly due to multiple integer execution units.
But when doing this on 16MHZ real-time microprocessor with neither branch prediction nor integer execution units there were notable differences.
1 million iterations of the slower code took 1761 ms
int slower(char *a, long i)
{
if (i < 0 || i >= 10)
return 0;
return a[i];
}
1 million iterations faster code took 1635 ms
int faster(char *a, long i)
{
if ((unsigned int)i >= 10)
return 0;
return a[i];
}