by loup-vaillant · 16y ago · 0 comments
void condense_by_removing(char* s, char c)
{
char* d = s;
while (*d = *s++)
d += *d != c;
}
I would have sworn I found a bug. There is none. Brilliant.Now, I wonder if we could further optimize it. For instance by accessing memory several bytes at a time, in a fashion similar to strcmp().
d += *d != c;
with a branch, and depending on the data pattern the branch predictor will be bamboozled. The branchless version would involve a pair of subtractions and some bit banging.Here's the code I tested. I think it works, but I barely checked it. I'm sure there are better ways to calculate 'increment'. Not sure if these would be enough to close the gap, though.
void condense_by_removing_branchless(char *z_terminated, char char_to_remove) {
char *condensed = z_terminated;
while (*z_terminated) {
*condensed = *z_terminated;
int diff = *condensed - char_to_remove;
int increment = -((diff | -diff) >> ((sizeof(int) * 8) - 1));
condensed += increment;
z_terminated++;
}
*condensed = 0;
}(I've not tested this though, I may be wrong.)
Works with gcc though.
Can somebody throw some light on how this works?
void condense_by_removing(char* s, char c)
{
char* d = s;
while (*d = *s++)
d += *d != c;
}
It always does the copy, then evaluates *d!=c. If what it just copied is equal to the forbidden character this evaluates as false, which in C is 0, and hence d is left unchanged.If what it copied is not equal then this evaluates as true, which is 1, and hence d is incremented.