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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With