Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is "switch" compiled? [duplicate]

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?

like image 538
Dirk Vollmar Avatar asked May 12 '26 01:05

Dirk Vollmar


1 Answers

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.

like image 65
Konrad Rudolph Avatar answered May 13 '26 14:05

Konrad Rudolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!