Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is switch performance over enum cases O(1)

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: ...
}
like image 432
MH175 Avatar asked Nov 23 '25 13:11

MH175


1 Answers

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:

enter image description here

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:

enter image description here

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).

like image 127
Rob Avatar answered Nov 26 '25 17:11

Rob



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!