Can anyone explain what the trade off (even if it’s negligible) would be between using if, if else, or switch in a sizable block of code similar to the following? Is the situation different if it were comparing a String or another Object instead of an int? The examples are in Java but it is meant as a general question.
EDIT
As several answers stated, a switch is going to be faster and should probably be used if there are more than a few cases. However, nobody has commented on if vs if else when in a long chain like this. What sparked this question is that I am frequently creating these blocks where a switch can’t be used because most of the cases require multiple expressions. I guess excluding the else feels sloppy, but it isn’t really necessary so why include it?
public String getValueString(int x) {
if (x == 1) return "one";
if (x == 2) return "two";
if (x == 3) return "three";
if (x == 4) return "four";
...
return null;
}
VS
public String getValueString(int x) {
if (x == 1) return "one";
else if (x == 2) return "two";
else if (x == 3) return "three";
else if (x == 4) return "four";
...
return null;
}
VS
public String getValueString(int x) {
switch(x) {
case 1: return "one";
case 2: return "two";
case 3: return "three";
case 4: return "four";
...
}
return null;
}
If you have a lot of cases, then the
switchapproach is the preferred method. The reason is because the first two requires essentially a linear search through all the if-statements. So it isO(N)to the number of cases you have.On the other hand,
switchstatements are optimized differently and can be eitherO(log(N))or evenO(1)for finding that correct case.How can the compiler achieve
O(log(N))or evenO(1)?O(log(N)).O(1).