1

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;        
}
Jacob Phillips
  • 8,841
  • 3
  • 51
  • 66
  • Any tag help would be appreciated. – Jacob Phillips Apr 17 '12 at 04:19
  • 3
    If you have a lot of them, `switch` is the way to go. – Mysticial Apr 17 '12 at 04:19
  • Instead of returning null, return "NaN" or "Undefined" ... – Prince John Wesley Apr 17 '12 at 04:22
  • 3
    In most cases I would say there is no noticeable difference. Micro-optimization...evil. In reality, it depends on the compiler. If you do this in .Net, you could use ILDASM to see what IL code is created by the compiler. The code might even be optimized to the same thing. Only one way to find out... – Jason Down Apr 17 '12 at 04:22
  • possible duplicate of [is "else if" faster than "switch() case"?](http://stackoverflow.com/questions/767821/is-else-if-faster-than-switch-case) – trutheality Apr 17 '12 at 04:32
  • 1
    Identification of a language for which the answer should be provided in is at least as important as the question itself. It is _rarely_ (if ever) applicable to tag unrelated languages regardless of the question content. If you want a solution for C# then ask a question about C#, if you want to ask a question about java then do so, but tagging both is an abuse of the language tags. – M.Babcock Apr 17 '12 at 04:32
  • The language-agnostic tag might be appropriate here, although in a question about relative performances, the language often makes a big difference. – trutheality Apr 17 '12 at 04:34

5 Answers5

7

If you have a lot of cases, then the switch approach is the preferred method. The reason is because the first two requires essentially a linear search through all the if-statements. So it is O(N) to the number of cases you have.

On the other hand, switch statements are optimized differently and can be either O(log(N)) or even O(1) for finding that correct case.


How can the compiler achieve O(log(N)) or even O(1)?

  • Binary search of the case values will allow it to be done in O(log(N)).
  • If the case values are dense enough, the compiler may even use a jump table indexed by the case variable. In that case it is O(1).
Mysticial
  • 464,885
  • 45
  • 335
  • 332
  • Your answer should probably say, _If you have a lot of cases based on a single variable_. 'switch' statements don't work so well when multiple, complex conditions must be met. – M.Babcock Apr 17 '12 at 04:24
  • Yes, that's true. The examples the OPs has provided are all single variable cases. – Mysticial Apr 17 '12 at 04:25
  • Of course, though your answer should be targeted to any future readers as well (or at least attempt to). +1 none the less. – M.Babcock Apr 17 '12 at 04:26
2

Most compilers will optimize the examples in your question to be nearly or even exactly the same. The issue, therefore, is one of readability.

If you have one or two cases, an if statement usually makes sense. If you have many, especially if the code for each case is small, then a switch statement tends to be more economical in terms of code required and can be easier to read.

But, at least up to a point, readability is a matter of personal preference.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
  • Isn't their really only _one_ compiler in question (at a time)? – M.Babcock Apr 17 '12 at 04:29
  • @M.Babcock, I don't understand the question. "At a time", there is only one or no compiler (as in the case of JavaScript). Did you interpret something I said to indicate there were multiple compilers at a time? – Jonathan Wood Apr 17 '12 at 05:35
2

Switch is faster than if/else blocks when it can be used. When there are more than 5 entries, it is implemented as a lookup. This provides some information regarding performance: Is "else if" faster than "switch() case"?

I believe it is also more readable in these cases.

Community
  • 1
  • 1
yamen
  • 15,390
  • 3
  • 42
  • 52
  • What is the claim that `switch` is faster based on, especially in the context of a question that is not really specific to any one language? Compilers often optimize code in ways that are not always intuitive. I would submit that there are cases, a `switch` statement can produce *exactly* the same machine code as for an `if` statement. – Jonathan Wood Apr 17 '12 at 05:38
  • I've read some more and of course you are write - the same optimisations can be made for if-else blocks also. I've upvoted your answer, but these discussions are useful for future visitors. – yamen Apr 17 '12 at 05:41
1

For the fewer items there will be no significant performance difference between if statements and switch statement. In switch statement every item is accessed directly, in same time, so the last item will take the same time as the first item. In if statement accessing the last item will take a longer time than the first one because it has to traverse through all the items before it. Anyway the latency will not be noticeable for fewer items as in your example.

Here is a good discussion on this topic. Have a look.

ABH
  • 3,391
  • 23
  • 26
0

If you have a large number of conditions similar to the ones in the provided examples, then I would recommend a Map.

Map<Integer,String> map = new HashMap<Integer,String>();
map.put(1,"one");
map.put(2,"two");
map.put(3,"three");
map.put(4,"four");

I am not sure about the trade-off. I would imagine it would behave similarly to a switch statement. It would reduce the cyclomatic complexity of your code which should make it more readable.

emory
  • 10,725
  • 2
  • 30
  • 58