Fast lookup table ideas

Nov 4, 2012 at 10:50pm
I need a really fast lookup table:

-it will accept a two digit hex number
-the first digit will locate the row of the table (1-F) and the 2nd the column (1-F)
-returns the value of that column/row.

At the moment I have something like this and it is way too slow:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

  int tolookup2 = tolookup; //find this number

    string inttostring;   
    stringstream hexout;
    hexout << hex<< tolookup2;
    inttostring = hexout.str();//convert to hex

   if (inttostring.length()==1)  //if less than 2 digits add 0 to start
   {


        inttostring.insert(0,"0");
   }

    int column,row;


    if (inttostring[0] >='0' && inttostring[0]<='9')  //if number 1-9
        row = inttostring[0] - 48;

    else
        row = inttostring[0] - 87;    //if a-f




     if (inttostring[1] >='0' && inttostring[1]<='9')
        column = inttostring[1] - 48;

    else
        column = inttostring[1] - 87;


        return table[row][column];  //table is the 2d array containing the table
  
}


There must be a faster way than this?

Any ideas would be great (hash tables?).
Last edited on Nov 4, 2012 at 10:51pm
Nov 5, 2012 at 12:17am
1
2
3
row = (tolookup >> 4) & 0xF;
column = tolookup & 0xF;
return table[row][column];
Last edited on Nov 5, 2012 at 12:18am
Nov 5, 2012 at 12:24am
You're looking for a 2D array. The fastest "hash table" out there is just an array, and based on how you need to index it that's exactly what you need.

1
2
3
std::vector<Data> myData (0xFF);
//It doesn't matter if the vector is actually "2D", since every combination of 
//"rows" and "columns" has a different index. 


To read hex just use:
1
2
3
int index;
std::cin >> std::hex >> index;
myData[index] = 42;
Nov 5, 2012 at 1:29am
The fastest possible way to do it is a straight, 1D array as suggested.

That said, I cannot imagine what kind of requirements you are under to convert a two-digit hexadecimal value faster than a couple of arithmetic operations for each digit.

Have you really profiled your program or are you playing "human optimizer"?
Nov 5, 2012 at 7:12am
Stringstream is horrendously slow.
Nov 5, 2012 at 10:28pm
Peter, that is about 230x faster than my code! Thank you!
Nov 6, 2012 at 12:56am
Stringstream is horrendously slow.


Let's not blame stringstream for your poor algorithmic choice.
Topic archived. No new replies allowed.