Switch out that Switch Case

Deepti Nagarkar
deeblueangel
Published in
2 min readAug 18, 2020

Anyone who does programming, would agree that the switch case construct is a very useful one , irrespective of the language. It is very convenient, easy to read and understand.

But, did you know it is also a bad performing construct? Especially if it is going to be executed multiple times or in a loop. The best case will be the first match. The worst case will be for the case which is matched at the last condition.

The time complexity will be (number of cases)^number of times the loop is executed. Or in Big O notation O(n) for worst case and O(1) for the best case.

But, there are ways to either avoid the switch case or tune it a bit.

Use Maps Instead

Many languages make a jump table from the switch case and use that to resolve the conditions. This is usually done at compile time. We can use a similar thing in our programs. Use a map and for every condition fetch the corresponding key-value. By doing this, we delegate the handling of time complexity to the underlying language platform.

Most Frequently Matched Case First

Identify the most common case that occurs in your application and keep it as the first one. Basically sort your cases in the descending order of occurrence, with the last one being the least occurring one. That way, the time taken for most of the cases will be reduced, and an overall efficiency could be achieved.

Use Enums/Constants for the Cases

This is more of a memory efficiency tip. For each of the cases, use Enums or String Constants.

Hope you find this helpful in your programming.

--

--