If vs. Switch Speed

Dirk Vollmar picture Dirk Vollmar · Jan 15, 2009 · Viewed 63.7k times · Source

Switch statements are typically faster than equivalent if-else-if statements (as e.g. descibed in this article) due to compiler optimizations.

How does this optimization actually work? Does anyone have a good explanation?

Answer

Konrad Rudolph picture Konrad Rudolph · Jan 15, 2009

The compiler can build jump tables where applicable. For example, when you use the reflector to look at the code produced, you will see that for huge switches on strings, the compiler will actually generate code that uses a hash table to dispatch these. The hash table uses the strings as keys and delegates to the case codes as values.

This has asymptotic better runtime than lots of chained if tests and is actually faster even for relatively few strings.