Is the switch statement faster than the if statement?

Shouman B. Shuvo

4 April, 2024

One fine late night, we were talking about whether we need the switch statement in our life. Also, we admitted that we had confusion in life about when to use the “if” and when to use the “switch”. It’s great to have confusion in our lives. It helps us to grow.

We forgot what we read in the compiler design course and some of us even chose another course over this one. What our simple mind thought was every if-else or switch-case is converted into CMP (Compare instruction) in assembly, so the performance should be the same.

However, I thought of writing a code that has 10,000 random values between 1 to 5, and I will be comparing them with the “if” statement first and then print something. I will be doing the same with the “switch” statement again. I will check the execution time difference between these two. I was too lazy to download the SDK on my machine, so I tried the Dartpad. Here’s what I got:

I ran this several times and found 1 millisecond improved performance. So, the “switch” is fast. But how?

This made me curious!!! I rewrote the same code in C and compiled it so assembly. I have found the exact things that I was expecting, 5 compare instructions.

But when I compiled the code with the switch statement. I found something interesting. There’s only one comparison instruction.

So, the codes of the “if” and the codes of the “switch” are not compiled the same! With the help of the Gemini, I tried to understand those lines (yes, I am not good at assembly). This is what Gemini explained to me:

  • Compares a local variable with 5.
  • Based on the comparison, it either exits the function or retrieves a value from an array based on another local variable.
  • Finally, it jumps to the location stored in the retrieved value, likely calling another function or continuing execution based on the outcome of the comparison.

 

So, this is what I have ended up with. The switch statement is faster because, unlike the if-else ledger, the switch-cases are compiled into a jump table. I could be wrong here, but I could relate it to the hash table. It’s like rather than multiple comparisons, it directly jumps into a memory address for the next executions, which servers a complexity of O(1). Though in most cases the complexity is O(1), it can be of O(n) based on the compiler and the language.

Shouman B. Shuvo

4 April, 2024