Faster Bound Checks
02/06/2022
In a recent pull request I received some comments on how to do bound checks better when indexing into arrays. The original code received a span and an index (scan). If the index was larger to the span's length, it returned minus one. Otherwise it indexes into the buffer and does a further lookup.
private static int ReadHex(int scan, ReadOnlySpan<char> buffer) { if (scan >= buffer.Length) return -1; int c = buffer[scan]; return c >= CharToHexLookup.Length ? -1 : CharToHexLookup[c]; }
After implementing the suggestion, the code looks nearly identical, but it is using uint
types for the comparing the index variable with the length of the bugger:
private static int ReadHex(int scan, ReadOnlySpan<char> buffer) { if ((uint)scan >= (uint)buffer.Length) return -1; int c = buffer[scan]; return c >= CharToHexLookup.Length ? -1 : CharToHexLookup[c]; }