Switch vs if comparison in Java - Performance Comparison
We want to see how the time it takes to run a switch or if statement changes as we add more choices.
Which one grows faster when there are many options?
Analyze the time complexity of the following code snippet.
int value = 3;
switch(value) {
case 1: System.out.println("One"); break;
case 2: System.out.println("Two"); break;
case 3: System.out.println("Three"); break;
default: System.out.println("Other");
}
if(value == 1) {
System.out.println("One");
} else if(value == 2) {
System.out.println("Two");
} else if(value == 3) {
System.out.println("Three");
} else {
System.out.println("Other");
}
This code checks a number and prints a message using both switch and if-else statements.
Look at how many checks happen before the right case runs.
- Primary operation: Comparing the value to each case or condition.
- How many times: Up to the number of cases (options) in the switch or if-else chain.
As the number of cases grows, the number of comparisons can grow too.
| Input Size (number of cases) | Approx. Comparisons |
|---|---|
| 10 | Up to 10 comparisons |
| 100 | Up to 100 comparisons |
| 1000 | Up to 1000 comparisons |
Pattern observation: The checks increase roughly in a straight line as more cases are added.
Time Complexity: O(n)
This means the time to find the right case grows directly with the number of choices.
[X] Wrong: "Switch statements are always faster than if-else chains no matter what."
[OK] Correct: Both can take longer as cases grow, and performance depends on how the code is compiled and used.
Understanding how choices affect speed helps you write clear and efficient code, a skill useful in many coding tasks.
What if we replaced the switch with a HashMap lookup? How would the time complexity change?