Are `switch` statements over `String` ever optimized to a hash table lookup?

Will a switch statements with a String input and String cases (or, more generally, where the input and cases are of a type that conforms to Hashable) ever be optimized to a hash-table lookup, or is it always compiled as a sequence of if-else statements?

I seem to remember someone saying it was never optimized, but now I can't find where I saw that. I also glanced through the compiler but couldn't find the relevant logic, can someone suggest where to look?

Check out StringSwitch.swift, specifically _findStringSwitchCaseWithCache. The cache is a Dictionary, so it's a hash-table lookup, but it only appears to apply to strings.

It gets used in SILOptimizer: https://github.com/apple/swift/blob/291364b2f1b81c100b155de900494780ed79bded/lib/SILOptimizer/Transforms/ObjectOutliner.cpp#L489

EDIT: It's only used for synthesised RawRepresentable conformances. There is a PR to expand this.

1 Like

While I know you were only asking about String, but for types that conform to Hashable there may be other, better optimisation targets. For example, for Swift enums and types that wrap integers it is very common for switch statements to optimise to jump tables, which is vastly preferable than hashing the data structure.