C# – Most efficient method for large switch statements

cefficiencyswitch statement

Let's say you have many paths that an application can take at a certain point based on the value of a specific input (for example a simple int). Is there a certain method that is most efficient for picking which path to follow? A nice and organized way would be a simple switch statement, but does that scale as the number of possible cases grows larger? Is there a better method when you have, say 100 or 1000 possible cases? Assume polymorphism isn't applicable and each case has totally unique functions which cannot be abstracted further.

Edit: Just to clarify, this is a thought experiment, I'm not actually writing code with 1000 cases. Also I found this related question to be enlightening on how the compiler/JIT handle the issue: Why use an OO approach instead of a giant "switch" statement?

Best Answer

I hope this is just a thought experiment, because if you have a real-wold program with a thousand distinct code path selected by an int parameter, performance considerations should be way down you list of worries. It sounds completely unmaintainable.

But to actually answer the question: switch is O(n). If you really want to scale you need a O(1) algorithm, so you create an array or dictionary which maps the integer values to delegates, pick the delegate based on the int, and executes it.

I was wrong: Apparently a switch with enough branches are compiled into a jump table or a dictionary lookup anyway. So you can't do faster than a switch.