Friday, July 1, 2011

if, if-else or switch-case ???

Consider the following cases in c#, supposing all integers:
Case 1:
if (x==1)
   value = 65;
if (x==2)
   value = 70;
if (x==3)
   value = 75;
if (x==4)
   value = 80;
Case 2:
if (x==1)
   value = 65;
else if (x==2)
   value = 70;
else if (x==3)
   value = 75;
else if (x==4)
   value = 80;
Case 3:
switch (x)
{
    case 1:
      value = 65;
      break;
    case 2:
      value = 70;
      break;
    case 3:
      value = 75;
      break;
    case 4:
      value = 80;
}
Which one would you prefer? Which one is most efficient and would also refrain from degrading performance?
Well many of you must be having your own logic and thinking of possibilities how one case can dominate the other. And many others (the diverse intellects), may also propose a method like this:

if (x > 0 && x < 5)
    value = 60 + x * 5;
C'mon its not about this specific piece of data here!!! Then which one? Yes! its the Switch Case which is the most optimized one :)
The if-else ladder process each of the if statements in the order specified by the developer. The compiler has an ability to optimize the switch case statement. As the switch cases are mutually independant among themselves, the compiler has the ability to re-order the testing providing fastest possible time. There is an interesting test done on the same which can be read here.
FYI, In the programming language C....yipeee......C, the compiler translates switch case to the xlat assembly instruction {as if you know what it means :D}

Ok. Fine. Nice.Very Nice. Awesome..... Stop!!! What if I don't actually want to slither in with those bunch of cases....long ones, also I desire to escape so much of if's out there?  :X

Well there's an alternative to Switch Case statements too then ---> Strategy Pattern. For the above case, we can maintain a Dictionary like:
 int x = 1;
  Dictionary<int, int> dict = new Dictionary<int, int>() {{1,65},{2,70},{3,75},{4,80}};
  int value = dict[x];
Further reading material for strategy pattern can be found out here. Applying strategy pattern helps us to prevent the horror of using endless switch cases or popularly referred to as the spaghetti code.

Now this doesn't really mean that you shake off all your if-else and abandon all you switch cases. Generally when your if or switch is repeatedly used then you should opt for applying design patterns. Remember there are always Trade-Offs involved in each and every facet of life.

No comments: