Home > Software engineering >  How is a switch statement more efficient than other conditional statements when checking for multipl
How is a switch statement more efficient than other conditional statements when checking for multipl

Time:11-04

i know that using a switch-case is more efficient than liniking else-if statements when checking multiple possible variable values. But what I dont know is how does it "jump" to the right value so fast. What type of function or protocol does it generally use?

Thanks.

CodePudding user response:

Take a look at this, it's explained quite well there:

When compiler compiles a switch statement, it will inspect each of the case constants and create a “jump table” that it will use for selecting the path of execution depending on the value of the expression.

https://www.geeksforgeeks.org/switch-vs-else/#:~:text=A switch statement is usually,a set of nested ifs.&text=The compiler can do this,compiler has no such knowledge.

CodePudding user response:

For a small number of conditions, the difference is quite small, but for many conditions you better use a switch. The reason is that when there are many values and conditions, it uses a hashtable/hashmap (a dictionary), it's a data structure with O(1) complexity of accessing the elements, to assure that all the values get the same access time. This is why switches are better than ifs when there are many conditions to check.

CodePudding user response:

For posting questions like How is <A> more efficient than <B> you have to be pretty sure that it in fact is true.

I bet I can come up with some examples for which if...else if... will perform better. For example, by benefiting from branch prediction.

Also, O(1) complexity can take longer then O(n), depending on the constant cost. And n, of course.

  • Related