

If-else vs switch – Which is better? - paliwalashish
http://www.ashishpaliwal.com/blog/2009/08/if-else-vs-switch-–-which-is-better/

======
tkho
This is complete garbage. Even allowing for it being a microbenchmark, each
iteration contains a System.out.println that takes thousands of times more
cycles than the conditional.

~~~
daeken
In addition, this varies greatly depending on the values you're matching
against (how efficiently can it be compiled?) and what compiler is being used,
even in just the Java space.

~~~
kulkarnic
And if you are using a JIT that optimizes frequent code; how easily the
branches are predictable and a host of other factors. Also, I don't think this
comparison is even useful: clearly if-else and switch-case have different use-
cases.

Some others have also hinted at using an array of function pointers and
indexing by switch variable. This looks cleaner, but is not necessarily
faster, since each call then involves chasing down a memory-pointer (this is
also the general argument against virtual functions).

I'm not sure how valid this C-argument is in Java world, but I believe pointer
chasing is a major performance problem (C# requires an explicit virtual
declaration on functions for the same reason).

~~~
haberman
> Some others have also hinted at using an array of function pointers and
> indexing by switch variable.

Doing this explicitly makes no sense -- I'm pretty sure the compiler will
compile the switch this way if its heuristics determine that it the fastest
way.

------
silvio
For most applications, the choice between an if-ladder and a switch statement
should be driven mostly by legibility and not performance. If performance is
at stake, I would look for I/O first, memory access patterns second, and
instruction sequencing last.

~~~
jacobolus
Which is really the case for almost all such choices, and the reason that we
generally favor languages with more expressive power and code clarity, rather
than raw speed, except in tight inner loops.

------
larryfreeman
Often times, there is a third choice: polymorphism using interfaces.

Consider an example from the article:

public static void testIfElse(int jumpLabel) {

if(1 == jumpLabel) {

    
    
        System.out.println("1");
    

} else if(2 == jumpLabel) {

    
    
        System.out.println("2");
    

} else if(3 == jumpLabel) {

    
    
        System.out.println("3");
    

} else if(4 == jumpLabel) {

    
    
        System.out.println("4");
    

}

// Removed for simplicity

else {

    
    
        System.out.println("default");
    

}

}

Why not implement this as follows:

public interface IfElse {

    
    
       public void testIfElse();
    

}

public class JumpLabelDefault implements IfElse {

    
    
       public void testIfElse() {
    
          System.out.println("Default"); 
    
       }
    

}

public class JumpLabel1 implements IfElse {

    
    
       public void testIfElse() {
    
          System.out.println("1");
    
       }
    

}

...

Then, to do the same test, you have this function:

public static void testIfElse(IfElse obj) {

    
    
       obj.testIfElse();
    

}

This is faster than either an if-else statement or a switch statement and you
can easily add new cases by creating new objects without needing to change the
previous code.

I'm not sure why this option is not included in the article.

~~~
gaius
And to think people say Java is verbose!

------
bkovitz
I don't understand how he gets his conclusion. The switch statements ran
faster by a factor of two or more. Isn't that a significant improvement in
performance?

------
wglb
I have now become accustomed to using COND which I would find a way to emulate
if I had to program in another language. I find too many errors in simple _if_
statements.

Plus, the switch seems to be inviting trouble, considering Duff's Device.

Oh, and I consider performance better if i get the correct result.

------
naz
lambdas in an array or hash :)

------
TweedHeads
Sometimes I have to use a hack in javascript to create a quick switch, instead
of if...else:

    
    
      if(n==0) dir="north"
      else if(n==1) dir="east"
      else if(n==2) dir="south"
      else if(n==3) dir="west"
    

or switch:

    
    
      switch(n){
        case 0: dir="north"; break;
        case 1: dir="east"; break;
        case 2: dir="south"; break;
        case 3: dir="west"; break; 
      }
    

I'll use:

    
    
      dir=["north","east","south","west"][n]
    

I hope you find it useful in some cases too

~~~
apu
This is similar to the accepted idiom in python as well: create a dictionary
mapping choices to outcomes.

For the special case of sequential numerical choices, a list works as well.

For the special- _special_ case of numerical choices for single-word string
outcomes, I often use:

    
    
      dir = 'north eash south west'.split()[n]

------
wizardofoz
Code that test the finite switch:

3\. for (int i = 0; i < iteration; i++) {

4\. testSwitchFinite(i);

5\. }

Once i > 5, testSwitchFinite will always skip to default. _This function
doesn't even test the switch properly._

Something like testSwitchFinite(i%5+1) would have made more sense (for the
finite switch and if-else.)

