I have a critical section of code which examines each char in many strings to ensure it falls in an acceptable range.
Is there any way i can perform such filtering without branching?
...
int i, c;
int sl = strnlen(s, 1023);
for( i = 0; i < sl; i++ ) {
c = s[i];
if( c < 68 || c > 88 )
return E_INVALID;
}
if( 0 == i )
return E_INVALID;
... do something with s ...
I was thinking some kind of filtering using bitwise operations might be possible, but in practice i can’t see how to make this work. Bitwise AND with 95 trims the range down to 0-31,64-95. i can’t see how to progress without introducing an if test, rendering the idea of skipping the branching void.
Assuming your strings are really unsigned chars, not ints, you could have a 256 byte lookup table of unacceptable characters, which would make your test if(table[s[i]]) { return E_INVALID; }
However, if you are trying to speed up a critical function, you should do other things for much bigger payoff. To start, you can skip the strnlen entirely, and terminate the loop on a 0 char. That alone will probably get you a factor of 2. Next unroll the loop by a factor of 10 or so, which ought to get another factor of 2.