If-else vs switch – Which is better?
ashishpaliwal.com
ashishpaliwal.com
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).
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.
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.
Plus, the switch seems to be inviting trouble, considering Duff's Device.
Oh, and I consider performance better if i get the correct result.
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 tooFor 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]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.)