First and foremost, I should point out that if you're doing performance work, you should profile the code to see where the slowdown is. That will allow you to determine objectively whether changes you make are actually helping or not.
You have 2 negations on your call to I had originally thought that the double negation of
isalpha(). If you remove them both, you'll get the same result, but faster.
isalpha() was pointless, but others have pointed out that it's needed because of quirks in the C language. Given that, and given that I don't recall ever running into this in the wild, I'd recommend reformulating it. There are a few options:
- Get rid of the
&= as mentioned below.
- Write a function that returns an actual
bool value so you don't have to worry about this particular quirk.
- Change the local call site to calculate a
bool by doing something like
alphabetic &= (isalpha(*c++) != 0);
- At the very least, comment on why you need the
!! in the first place since it's not immediately obvious.
You could exit the loop early at the first non-alphabetic character. So something like:
while ((*c) && (alphabetic))
alphabetic &= isalpha(*c++);
A local in-line implementation of
isalpha() is likely to be faster than a
system library call. Of course, that makes maintenance harder because you have to have a different version for each encoding, given the possibility of non-contiguous
a-z characters. A simple way, if you can guarantee 8-bit characters, is to have a 256 element lookup-table where each element is true or false. You could automatically build it by doing something like:
for (int nextChar = 0; nextChar < 256; nextChar++)
alphaTable[nextChar] = isalpha(nextChar);
Then your loop becomes:
bool alphabetic = true;
while((*c) && (alphabetic))
alphabetic = alphaTable[*c++];
You can get rid of the
&= because whenever it becomes false, 1) we're done, and 2) all future values will be false.
This could be made even faster by using SIMD instructions. The details would vary depending on the architecture, so again, more maintenance. If you have a very large number of strings to calculate this on at one time, you could also perform multiple simultaneous calculations by running the function on multiple cores at the same time.