function thing(e) {
switch (e) {
case 0:
return "0";
case 1:
return "1";
case 2:
return "2";
case 3:
return "3";
default:
return "";
}
}
for (let t = 0; 1e5 > t; t++) thing("0"), thing("2"), thing("");
function bounce(x)
{
if (x === 0) return "0";
if (x === 1) return "1";
if (x === 2) return "2";
if (x === 3) return "3";
return ""
}
for (let t = 0; 1e5 > t; t++) bounce("0"), bounce("2"), bounce("");
function bounce(x) {
return 0 === x ? "0" : 1 === x ? "1" : 2 === x ? "2" : 3 === x ? "3" : "";
}
for (let t = 0; 1e5 > t; t++) bounce("0"), bounce("2"), bounce("");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
switch case | |
bounce patttern | |
ternary |
Test name | Executions per second |
---|---|
switch case | 22564.5 Ops/sec |
bounce patttern | 22664.0 Ops/sec |
ternary | 22600.7 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
The provided JSON represents a benchmark test that compares the performance of three different approaches for implementing a simple switch-case statement: the traditional switch
statement, the "bounce pattern" (also known as the "hash table" approach), and the ternary operator.
Switch Statement
The traditional switch
statement is implemented using a switch
expression inside an array loop. This implementation uses the case
labels to determine which value to return for each iteration of the loop.
function thing(e) {
switch (e) {
case 0:
return "0";
case 1:
return "1";
case 2:
return "2";
case 3:
return "3";
default:
return "";
}
}
Bounce Pattern
The "bounce pattern" is a common optimization technique for switch statements. Instead of using multiple case
labels, it uses an array to store the values and their corresponding results. The function iterates over this array and returns the result for each value.
function bounce(x) {
const values = ["0", "1", "2", "3"];
const results = ["", "", "", ""];
for (let i = 0; values[i] !== undefined; i++) {
if (x === values[i]) return results[i];
}
}
Ternary Operator
The ternary operator is a concise way to implement the same logic as the switch
statement using a single expression.
function bounce(x) {
return 0 === x ? "0" : 1 === x ? "1" : 2 === x ? "2" : 3 === x ? "3" : "";
}
Pros and Cons
Here's a brief summary of the pros and cons of each approach:
case
labels.Library Considerations
None of the above implementations use any external libraries.
Special JS Features
The provided benchmark tests only uses standard JavaScript features. No special features like async/await
, Web Workers, or Service Workers are used.
Alternatives
If you're looking for alternative approaches to implement a switch statement, here are some options:
map()
or reduce()
to implement the switch statement.These alternatives may offer different trade-offs in terms of performance, readability, and maintainability.