Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Possible Duplicate:
Should I use switch statements or long if…else chains?

I'm working on a small program that will conduct an Insertion Sort. A number will be inputted through the keyboard and stored in a variable I called "num." I've decided to use a switch statement in order to obtain the number inputted.

switch( e.getKeyCode() ) {

    case KeyEvent.VK_0: num = 0; break;
    case KeyEvent.VK_1: num = 1; break;
    case KeyEvent.VK_2: num = 2; break;
    case KeyEvent.VK_3: num = 3; break;
    case KeyEvent.VK_4: num = 4; break;
    case KeyEvent.VK_5: num = 5; break;
    case KeyEvent.VK_6: num = 6; break;
    case KeyEvent.VK_7: num = 7; break;
    case KeyEvent.VK_8: num = 8; break;
    case KeyEvent.VK_9: num = 9; break;
}

I realized one other course of action could have been to use a set of if statements.

if( e.getKeyCode() == KeyEvent.VK_0 )
    num = 0;
else if( e.getKeyCode() == KeyEvent.VK_1 )
    num = 1;
etc. for every number up until 9.

I then wondered what the essential difference is between a switch statement and a series of if statements. I know it saves space and time to write, but it's not that much. So, my question is, aside from the space, does a switch statement differ from a series of if statments in any way? Is it faster, less error-prone, etc.?

This question really doesn't affect my code that much. I was just wondering. Also, this question pertains to the JAVA language, not any other programming language.

share|improve this question

marked as duplicate by Ryathal, Thomas Owens Jun 27 '12 at 17:42

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

4 Answers 4

up vote 11 down vote accepted

You are correct that functionally they are identical. Practically speaking though, why would you type (or cut and paste) all that when a switch statement is so much more concise?

The difference is not one of functionality, but of intent. When you write a switch statement, you are in effect telling the reader that this section of code could branch multiple ways based on the state of one single variable. This statement is enforced by the compiler.

When you write an if block, however, you are not deliberately stating that only one variable is involved. When you write a series of ifs, as you suggest, it is much harder to see that the branching is only based on a single variable. This is a maintenance problem. Developers that have to modify your code in the future may not realize that you intended that decision to be so focused and will start adding conditions that are not using that variable. Someone will come along and say, "I want num to equal 10 if the last key sequence was 5-4-8," and tack an additional else if on the end of your block. Eventually that section will become a Gourdian knot of if...else if conditions that no one can understand. The future will hate you and bad karma will be added to your account.

Use a switch statement when possible. It clearly communicates that this section of code relies on a single variable and is much more future-proof.

share|improve this answer
    
You are not correct. There is a functional different. A switch compiles into a lookup table which is fundamentally different then the if/else statements. If the last statement in a if/else chain is the one you want you have to check all the previous if/else first. This is not the case with a switch. –  Andrew Finnell Jun 27 '12 at 20:59
1  
Terminological comment: I wouldn't call this a functional difference as the result of both if and switch will be the same. From what you say the difference, is in how it is translated by the compiler. –  dzieciou Jan 5 '13 at 13:26
    
And from similar post I see there might be no significant performance gains from switch. –  dzieciou Jan 5 '13 at 13:29

The power of switch is twofold:

  1. It is more descriptive
  2. It saves CPU cycles

Your post already comments on the descriptiveness of switch compared to a chain of ifs, so I will concentrate on part 2.

If the number of switch labels is N, a chain of ifs takes O(N) to dispatch, while a switch always dispatches in O(1). This is how it is done: compiler places addresses of switch labels into an array, computes an index based on the label values, and performs a jump directly, without comparing the switch expression to value one by one. In case of strings used as switch labels, the compiler produces a hash table, which looks up an address in O(1) as well.

When the number of switch becomes high (above 100), converting between switch and a chain of ifs could no longer be regarded as a micro-optimization: time savings may be very significant, especially in tight loops. If a profiler tells you that your chain of ifs is taking a significant time, rewriting as a switch may very well be a solution.

share|improve this answer
    
+1 Not sure why the other answers got the +1's as they are incorrect. This is the fundamental difference. –  Andrew Finnell Jun 27 '12 at 21:00
    
But don't you think that a decent compiler can and should perform this optimization since a) switch statements are more difficult to read than if..else and b) the syntax for switch statements is difficult to remember. –  909 Niklas Dec 3 '12 at 3:59

Some people feel switch reads more easily than if-else. But I agree with the belief that worrying about performance is in the realm of micro-optimization.

SO Java version of this Q
SO Java version of this Q v2
SO C++ version of this Q
SO C++ version of this Q v2
SO C# version ...

share|improve this answer
    
+1 just because I think this answer should have zero, not -1. Agreed regarding micro-optimization. It's insane how arbitrary all of this is, but really, switch vs. if? Gotta be a non-issue... –  Yar Aug 16 '12 at 17:48

A switch can be more efficient than a series of if/else if statements. See this article for an example in C. The big difference is that with if statements, the condition for each case can be anything. For example, you could write code that's the equivalent of:

If it's raining, put on a jacket, otherwise if it's a Sunday, call your mother.

With a switch, though, each comparison is going to be a test for equivalence, and the only thing that changes is the value that you're comparing to. As the link explains, if the values for the cases are all close to each other, the compiler may implement the switch using a jump table. That is, the compiler can use the value that you're switching on to directly calculate the address of the code for that case. That avoids the need for a sequence of comparisons. Now, a really smart compiler could notice that you're using a series of if statements the same way and do the same thing; I don't know if that's a common optimization or not.

All that said, I wouldn't worry too much about the code that the compiler generates. Instead, choose between if and switch according to what seems natural for you and the other programmers. A switch represents a choice of one case out of some number of cases where each case has a corresponding value. It's a demultiplexer. If you find that you've got a sequence of if statements that all have the same condition except for the value that you're comparing, a switch can be a nicer, shorter, more obvious way to express that.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.