towards a faster isdigit()

Stephen Clamage steve at taumet.com
Thu May 9 01:41:58 AEST 1991


eggert at twinsun.com (Paul Eggert) writes:

>The traditional implementation of isdigit() in <ctype.h> is typically
>something like this:

>	#define isdigit(c) ((_ctype_+1)[c] & 4)

>which requires indexing through a global array followed by a masking
>operation.  Why not use the following implementation instead?

>	#define isdigit(c) ((unsigned)((c)-'0') < 10)

>This needs just a subtraction followed by a comparison.  It's faster on
>all the systems I've tried it on, and is strictly conforming ANSI C.

Maybe you didn't try it on enough systems :-)

The macro you suggest requires a test and jump, and on some modern RISC
machines the penalty is very high.  For example, I tried a loop which
only tested for isdigit and incremented a global based on the test.  On
a Sun-4 (SPARC), the program using your macro took 44% longer than the one
using the usual ctype macro.  On a DECStation (MIPS), your macro took
46% longer.

This points up the principle that you shouldn't diddle your code looking
for small speedups based on characteristics of the compiler or target
machine.  Your attempts may backfire badly when the code is re-used.
(I'm not accusing Paul of diddling, I just like to make this point.)

Apart from that, the other ctype tests (except isascii) are always faster
using the lookup table, and it is simpler to use a uniform set of macros.
-- 

Steve Clamage, TauMetric Corp, steve at taumet.com



More information about the Comp.lang.c mailing list