5

I know switch statements are not available in CodeDom and how compilers deal with switch statement.

So for performance reasons when many cases are present, I don't want to use If-else
Why the switch statement and not if-else?

Is is possible to generate code to simulate a Jump table for a given case list.

switch(value) {
    case 0: return Method0();
    case 1: return Method1();
    case 4; return Method4();
}

Would produce:

    private delegate object Method();

    Method[] _jumpTable = new Method[] { Method0, Method1, null, null, Method4 };

    private object GetValue(int value)
    {
        if (value < 0 || value > 4) 
            return null;
        return _jumpTable[value]();
    }

What is the best way to analyze the case list and generate an array if there are holes in the sequence or the list is sparse?

Community
  • 1
  • 1
Eric Biron
  • 77
  • 7

1 Answers1

2

You might want to take a look at The Roslyn Project for the code anaylsis. If the table is large and especially sparse then if/else might be better (given modern CPU caches). Roslyn should let you walk the DOM and acquire the case values which can then be sorted (perhaps in a single linq stmt). I believe that you mean to have 'break;'s in your switch above. If you implement something like this I would test it very carefully to ensure that it actually does improve performance.

Dweeberly
  • 4,668
  • 2
  • 22
  • 41