Search code examples
c++charlookup-tables

c++ isalpha lookup table


Whats the easiest way to implement a lookup table that checks to see if a character is an alpha or not using a lookup table with an array 256 chars (256 bytes)? I know I can use isalpha function, but a lookup table can supposedly be more efficient, requiring one comparison instead of multiple ones. I was thinking of corresponding the index with the char decimal conversion and checking directly if it the char was equivalent to that.


Solution

  • Remember the first rule of optimisation: don't do it.

    Then remember the second rule of optimisation, to be applied very rarely: don't do it yet.

    Then, if you really are encountering a bottleneck and you've identified isalpha as the cause, then something like this might be faster, depending on how your library implements the function. You'll need to measure the performance in your environment, and only use it if there really is a measurable improvement. This assumes you don't need to test values outside the range of unsigned char (typically 0...255); you'll need a bit of extra work for that.

    #include <cctype>
    #include <climits>
    
    class IsAlpha
    {
    public:
        IsAlpha()
        {
            for (int i = 0; i <= UCHAR_MAX; ++i)
                table[i] = std::isalpha(i);
        }
    
        bool operator()(unsigned char i) const {return table[i];}
    
    private:
        bool table[UCHAR_MAX+1];
    };
    

    Usage:

    IsAlpha isalpha;
    
    for (int i = 0; i <= UCHAR_MAX; ++i)
        assert(isalpha(i) == bool(std::isalpha(i)));