case statement efficiency in c

c, performance, switch-statement

Solution

Disassemble the compiled code and see what the compiler does. I've looked at the output from several different compilers and large switch statements were always compiled into binary decision trees or jump tables. Jump tables are the most optimal thing you can get and they are more likely to be generated by the compiler if the values you're switching on are in a narrow range. It also helps have a default statement on some compilers (but not necessary on others).

This is one situation where disassembling is your only good option, the details of code generation on this level are rarely well documented.

Problem

I have a large switch statement, with about 250 cases, in Visual C: ``` #define BOP -42 #define COP -823 #define MOP -5759 int getScarFieldValue(int id, int ivIndex, int rayIndex, int scarIndex, int reamIndex) { int returnValue = INT_MAX; switch (id) { case BOP : returnValue = Scar[ivIndex][rayIndex].bop[scarIndex][reamIndex]; break; case COP : returnValue = Scar[ivIndex][rayIndex].cop[scarIndex][reamIndex]; break; case MOP : returnValue = Scar[ivIndex][rayIndex].mop[scarIndex][reamIndex]; break; ..... default: return(INT_MAX); } } ``` The #defines, you will notice, have a huge range, from -1 to -10,000. The thing is dog slow, and I'm wondering if spending several hours redefining these 250 defines to a narrower (or even consecutive) range could speed things up. I always thought the compiler would treat the case values in a way that made their numeric value irrelevant, but I have not been able to find any discussion to validate/invalidate that assumption.

Original source