Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch statement in codeDom (jump table style)

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?

like image 750
Eric Biron Avatar asked Nov 03 '22 09:11

Eric Biron


1 Answers

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.

like image 81
Dweeberly Avatar answered Nov 15 '22 18:11

Dweeberly