Thursday, June 11, 2015

Performance of switch and if-else ladder

What is the fastest way to implement conditional clauses in JAVA?

Answer : SWITCH  :) But in an even contest.

Almost all the times it is much more efficient to use SWITCH instead of IF-ELSE.
But the contest is important. We are talking about an incident where you use only one variable to check for equivalence with one value.(As shown in the following example)

There is a difference in the view of the INTENT. That is switch can only be used for one variable and only for equivalence. But if-else is different. You can use more than one variable and compare in different ways with different conditions. So it is not fair to compare the performance of a complex if-else control flow and a switch. What we are talking in this short article is the FUNCTIONAL difference in the low level between these two control flow structures.

Yet in an even contest switch is considered to be more efficient. Sure, you may have heard this somewhere, but you may not know why? Well, that may be the only reason you are here.

Lets' dig deep a little.

Though we code in English, the machine understands bits. So the compiler compile and change our English code into machine code via assembly. It is how the 'if-else' ladder and 'switch' is organized at this point, that make switch more efficient. 

There are few defferent opcodes for if-else implementation. Every one compares two values and if succeeds do a jump (I.E branching) to the offset given as an operand in the comparison opcode.  The success of comparison is decided by the opcodes.

Lets take an even example for both scenarios.

if (counter == 5){// do stuff}
else if (counter ==10){//do stuff}
else if(counter ==15){//do stuff}
else{//default stuff}
case 5 :
{// do stuff}
case 10 :
{//do stuff}
case 15 :
{//do stuff}

You can see the difference of the coding structure. Though the simplest control (in the code level) flow structure is if-else, in the byte level the simplest is switch.

A switch generates a hash-table with key,value pair (case value and branch offset pairs)or a binary search tree. In the case of hash-table time to find out the branch offset is always O(1). In the case of binary search tree the time complexity will be log(n). The difference is between table-switch and lookup-switch respectively.

Here n is the number of cases in the ladder.