Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "else if" faster than "switch() case"? [duplicate]

I'm an ex Pascal guy, currently learning C#. My question is the following:

Is the code below faster than making a switch?

int a = 5;  if (a == 1) {     .... } else if(a == 2) {     .... } else if(a == 3) {     .... } else if(a == 4) {     .... } else     .... 

And the switch:

int a = 5;  switch(a) {     case 1:         ...         break;      case 2:         ...         break;      case 3:         ...         break;      case 4:         ...         break;      default:         ...         break;   } 

Which one is faster?

I'm asking, because my program has a similar structure (many, many "else if" statements). Should I turn them into switches?

like image 361
Ivan Prodanov Avatar asked Apr 20 '09 11:04

Ivan Prodanov


People also ask

Is switch case faster than if-else?

As it turns out, the switch statement is faster in most cases when compared to if-else , but significantly faster only when the number of conditions is large. The primary difference in performance between the two is that the incremental cost of an additional condition is larger for if-else than it is for switch .


2 Answers

For just a few items, the difference is small. If you have many items you should definitely use a switch.

If a switch contains more than five items, it's implemented using a lookup table or a hash list. This means that all items get the same access time, compared to a list of if:s where the last item takes much more time to reach as it has to evaluate every previous condition first.

like image 151
Guffa Avatar answered Oct 11 '22 09:10

Guffa


Why do you care?

99.99% of the time, you shouldn't care.

These sorts of micro-optimizations are unlikely to affect the performance of your code.

Also, if you NEEDED to care, then you should be doing performance profiling on your code. In which case finding out the performance difference between a switch case and an if-else block would be trivial.

Edit: For clarity's sake: implement whichever design is clearer and more maintainable. Generally when faced with a huge switch-case or if-else block the solution is to use polymorphism. Find the behavior that's changing and encapsulate it. I've had to deal with huge, ugly switch case code like this before and generally it's not that difficult to simplify. But oh so satisfying.

like image 32
Wedge Avatar answered Oct 11 '22 07:10

Wedge