Jump Table Switch Case question

前端 未结 6 595
孤街浪徒
孤街浪徒 2020-12-08 00:55

I am trying to understand some things about jump tables and its relationship between a switch case statement.

I was told that a jump table is a O(1) structure that t

6条回答
  •  独厮守ぢ
    2020-12-08 01:53

    A jump table is basically an array of pointers to pieces of code to handle the various cases in the switch statement. It's most likely to be generated when your cases are dense (i.e. you have a case for every possible value in a range). For example, given a statement like:

    switch (i) {
       case 1: printf("case 1"); break;
       case 2: printf("case 2"); break;
       case 3: printf("case 3"); break;
    }
    

    it could generate code roughly equivalent to something like this:

    void case1() { printf("case 1"); }
    void case2() { printf("case 2"); }
    void case3() { printf("case 3"); }
    
    typedef void (*pfunc)(void);
    
    pfunc functions[3] = {case1, case2, case3};
    
    if ((unsigned)i<3)    
        functions[i]();
    

    This has O(K) complexity. A typical hash table also has roughly O(K) expected complexity, though the worst case is typically O(N). The jump table will usually be faster, but it will usually only be used if the table will be quite dense, whereas a hash table/dictionary works quite well even when the cases would be quite sparse.

提交回复
热议问题