HomeSearch

JavaScript switch Statement

Select a case in the switch statement. Compare the switch to an if-else block.
Switch. Consider a variable. Its value may be 10, 20 or 30. We can test this in a switch statement, and this may offer optimal performance.
JavaScript today is a compiled language. Is it worth using a switch statement (on integers) instead of a series of if-else tests?
First example. It is good to start with a simple example. Here we see a switch statement inside a function called testValue. We pass an integer to testValue.

And: The switch statement determines what value to return based on the argument.

Note: If no cases match, the switch is exited. We then reach the "return 0" so the value zero is returned.

JavaScript program that uses switch in function function testValue(value) { "use strict"; // Switch on the argument to return a number. switch (value) { case 0: return -1; case 1: return 100; case 2: return 200; } return 0; } // Call testValue. console.log("SWITCH RESULT: " + testValue(0)) console.log("SWITCH RESULT: " + testValue(2)) Output SWITCH RESULT: -1 SWITCH RESULT: 200
Default. A case matches just one value—an integer or string. But the default case matches all other values. It is an "else" clause in the switch.
JavaScript program that uses default var number = 5; // Use a default case in this switch. switch (number) { case 4: document.write("four; "); break; default: document.write("not four; "); } Output not four;
Last break statement. In JavaScript the last break statement is not required. The last case statement will execute without a break and no errors will occur.

Note: Fall through occurs when no break is present, but for the last case (often "default") this will not change behavior.

Performance: In a brief test, I found that Google Chrome has no performance change if you omit the last break statement.

JavaScript program that omits last break function test(value) { // No break statement is required on the last case. switch (value) { case 0: document.write("zero; "); break; case 1: document.write("one; "); break; case 2: document.write("two; "); } } test(0); test(1); test(2); Output zero; one; two;
Test, if versus swift. Here we use 2 complete HTML pages. We test the numbers 0 through 4 in an if-statement and a switch statement. Each case occurs the same number of times (20%).

Tip: To run the benchmark, paste the top program into a file and refresh the browser. Then try the bottom file.

Result: The switch program is noticeably faster. This is true in many browsers, including Safari, Firefox and Chrome.

JavaScript program that benchmarks if var x1 = performance.now(); var y = 0; for (i = 0; i < 1000000; i++) { for (z = 0; z <= 4; z++) { if (z == 0) { y++; } else if (z == 1) { y--; } else if (z == 2) { y += 2; } else if (z == 3) { y -= 2; } else if (z == 4) { y += 3; } } } var x2 = performance.now(); document.title = (x2 - x1) + "/" + y; JavaScript program that benchmarks switch var x1 = performance.now(); var y = 0; for (i = 0; i < 1000000; i++) { for (z = 0; z <= 4; z++) { switch (z) { case 0: y++; break; case 1: y--; break; case 2: y += 2; break; case 3: y -= 2; break; case 4: y += 3; break; } } } var x2 = performance.now(); document.title = (x2 - x1) + "/" + y; Output If/else if = 36.9 ms Switch = 27.4 ms
Benchmark, fall-through. How does fall-through affect switch performance? Sometimes we can add duplicate statements to cases to avoid fall-through.

Here: The first program omits the "break" in case 0, so that when case 0 is reached, case 1 is also reached.

Next: The second program just duplicates the increment statements in case 0 to avoid fall-through.

Result: The two programs are almost the same speed in Chrome but when no fall-through occurs, slightly less time is used.

JavaScript program that tests fall-through var x1 = performance.now(); var count1 = 0; var count2 = 0; // This switch has a fall-through case. for (var i = 0; i < 10000000; i++) { for (var x = 0; x < 3; x++) { switch (x) { case 0: count1++; case 1: count2++; break; case 2: count1 = 0; count2 = 0; break; } } } var x2 = performance.now(); document.title = x2 - x1; JavaScript program that tests no fall-through var x1 = performance.now(); var count1 = 0; var count2 = 0; // This switch has a break on all cases. for (var i = 0; i < 10000000; i++) { for (var x = 0; x < 3; x++) { switch (x) { case 0: count1++; count2++; break; case 1: count2++; break; case 2: count1 = 0; count2 = 0; break; } } } var x2 = performance.now(); document.title = x2 - x1; Output 101.62 fall through 101.98 102.05 99.69 no fall through 99.51 100.48
Performance, string switch. Here are 3 programs. They all loop over a string array multiple times. They all match each element in the array against one of three strings.

Program 1: This uses a switch statement. Sum (a variable) is adjusted based on the value of each string element.

Program 2: This uses an if-else chain. The array element is accessed repeatedly for many of the string values.

Program 3: This uses a local variable and then tests that in an if-else chain. It reduces array element lookups.

JavaScript program that uses string switch var x1 = performance.now(); var keys = ["abc", "def", "ghi"]; var sum = 0; for (var i = 0; i < 1000000; i++) { for (var k = 0; k < keys.length; k++) { switch (keys[k]) { case "abc": sum++; break; case "def": sum++; break; case "ghi": sum -= 2; break; } } } var x2 = performance.now(); document.title = (x2 - x1) + "/" + sum; JavaScript program that uses if, else var x1 = performance.now(); var keys = ["abc", "def", "ghi"]; var sum = 0; for (var i = 0; i < 1000000; i++) { for (var k = 0; k < keys.length; k++) { if (keys[k] === "abc") { sum++; } else if (keys[k] === "def") { sum++; } else if (keys[k] === "ghi") { sum -= 2; } } } var x2 = performance.now(); document.title = (x2 - x1) + "/" + sum; JavaScript program that uses var, if, else var x1 = performance.now(); var keys = ["abc", "def", "ghi"]; var sum = 0; for (var i = 0; i < 1000000; i++) { for (var k = 0; k < keys.length; k++) { var key = keys[k]; if (key === "abc") { sum++; } else if (key === "def") { sum++; } else if (key === "ghi") { sum -= 2; } } } var x2 = performance.now(); document.title = (x2 - x1) + "/" + sum; Output 328 ms switch 337 ms 342 ms 386 ms if, else 399 ms 389 ms 435 ms var, if, else 387 ms 401 ms
Results, string switch. The switch statement on strings is clearly faster here. In the second two programs, I did not see a benefit from placing the array element in a local variable.

So: When possible, use a switch for strings. The results here seem to indicate a string can be matched faster with a switch statement.

Lookup tables. An object can be used instead of a switch statement to look up anonymous functions. We then call those functions. This appears to be slower than a switch statement.function Lookup
A summary. JavaScript optimization is a moving target. Browsers improve performance every few months. Switch on integers, though, could be a performance win that lasts.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls