I couldn't come across information regarding performance of a switch statement over all enum cases. Say you have 100 cases. Is it O(1)?
enum MyEnum {
case one = 1
case two = 2
}
let myEnum = MyEnum.one
switch myEnum {
case .one: ...
case .two: ...
}
Looking at the assembly code (“Debug” » “Debug Workflow” » “Always Show Dissembly”) for the switch statement, one can see that it is O(1) (at least in this simple case, at least). For example, here is the switch code:

Don’t get lost in that code, but note that it’s very few instructions that set the contents of rdx to be the address of the code associated with that particular case:

The details here aren’t really relevant, but the key is that in my enumeration with 1,000 cases, it didn’t run through 1,000 tests but rather it calculated the address by calculating from index in this enumeration, and just jumped to the relevant code.
All of this having been said, enumerations usually don’t generally have enough cases that the complexity of the switch statement would ever be observable. And if you did have thousands (or millions) of different cases, there would be so many other problems with the code, that the complexity of the switch statement would be the last of your concerns, even if it weren’t O(1).
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