Switch vs if comparison in Javascript - Performance Comparison
We want to see how the time it takes to run code changes when using switch statements versus if statements.
Which one grows faster as we add more conditions?
Analyze the time complexity of the following code snippet.
function checkValueSwitch(value) {
switch(value) {
case 1: return 'One';
case 2: return 'Two';
case 3: return 'Three';
case 4: return 'Four';
default: return 'Other';
}
}
function checkValueIf(value) {
if (value === 1) return 'One';
else if (value === 2) return 'Two';
else if (value === 3) return 'Three';
else if (value === 4) return 'Four';
else return 'Other';
}
This code checks a number and returns a word using either a switch or if-else chain.
Look at how many checks happen before a result is found.
- Primary operation: Comparing the input value to each case or if condition.
- How many times: Up to the number of conditions (4 in this example).
As the number of conditions grows, the checks increase.
| Number of Conditions (n) | Approx. Checks |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The number of checks grows roughly in a straight line with the number of conditions.
Time Complexity: O(n)
This means the time to find the right case grows directly with how many conditions there are.
[X] Wrong: "Switch statements are always faster than if-else chains because they look cleaner."
[OK] Correct: Both switch and if-else check conditions one by one in simple cases, so their time grows the same way as conditions increase.
Understanding how condition checks grow helps you explain your choices clearly and shows you think about code efficiency in real situations.
"What if we replaced the switch with a lookup object (like a dictionary)? How would the time complexity change?"