Monday, December 1, 2014

switch vs if-else

Well, this one has been talked about a millions of times in different forums over the internet, many books also deals with this information as well. With a basic Google search capability you can get a tons of results. But for you, I would love tell you the same story over and over again...

Questions come as follows:
If-else are good in programming, they can deal with logic as expected, then what is the need of having switch-case ?
Both deal with logic and the output of the both are also same but the ways they work are different.
If-else is simply a sequential way of checking every block where switch maintains a hashtable( some call it as jump table ) with different known input/output mapping.
So, this way the switch statements are way faster than If-else ladder in case of larger number of If-else blocks. It is quite obvious and best suited to use switch statements if your code is having more than 6 If-else construct. 6 is not a magic number here. It basically an average result.

Why it is faster ?
In case of If-else the logic is tested for each block until it comes to an equality. On the other hand, switch-case creates a table with known input/output at compile time.
Thus the complexity of switch-case is O(1) while in case of If-else it is a factor of O(n).
The best case for an If-else is if it encounters the first logic block to be true while the worst case is if it encounters the last logic block to be true.
Well there is some overhead to create the hashtable in compile time, which causes some delay. So, 6 is the number you can follow as mentioned earlier.
The next thing you can think is the way switch-case and if-else is written in the code.
if-else is for boolean expressions where switch-case is for integral numbers, characters, enums and String (Java 7 feature).

So, if you are dealing with anything other than switch-case support, you are bound to do the same in if-else.

Where to use what ?
As mentioned, 6 is the number you can consider and keep in mind the switch-case support.
Another check you should do is the way your code needs decision making. For a hint, null check is a point you can consider if-else. Cause, switch-case misses this area.

Palash Kanti Kundu Palash Kanti Kundu Palash Kanti Kundu Palash Kanti Kundu Palash Kanti Kundu Palash Kanti Kundu Palash Kanti Kundu Palash Kanti Kundu Palash Ka Palash Kanti Kundunti Kundu

No comments:

Post a Comment