const input = 10;
switch(input) {
case 1:
return true;
case 2:
return true;
case 3:
return true;
case 4:
return true;
case 5:
return true;
case 6:
return true;
case 7:
return true;
case 8:
return true;
case 9:
return true;
case 10:
return true;
}
const input = 10;
const LUT = new Map([
[0, true],
[1, true],
[2, true],
[3, true],
[4, true],
[5, true],
[6, true],
[7, true],
[8, true],
[9, true],
[10, true],
])
LUT.get(input);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Switch | |
Map |
Test name | Executions per second |
---|---|
Switch | 197336128.0 Ops/sec |
Map | 4868720.5 Ops/sec |
What is being tested?
The provided benchmark tests the performance of two approaches to handle different input values: using a switch
statement and using a Map
data structure.
Options compared
Two options are compared:
switch
statement is used to check the value of the input variable and execute a corresponding block of code.Map
object is created with key-value pairs, where each key corresponds to an input value (from 0 to 10), and the function tries to retrieve the value associated with the input using the get()
method.Pros and Cons
Other considerations
In addition to performance, other factors to consider when choosing between these two approaches include:
Map
might be more suitable.Library and special JS feature
The benchmark uses no external libraries or special JavaScript features beyond the standard JavaScript syntax. However, the use of const
for declaring variables is a recent feature (ECMAScript 2015) that may not be supported in older browsers.
Benchmark preparation code
The provided script preparation code is empty, which means that the benchmark assumes the input variable is already defined and passed as an argument to the function. In a real-world scenario, you would typically add some setup code to define the input variable and any necessary data structures (e.g., maps).
Alternative approaches
Other alternatives for handling different input values could be:
hasOwnProperty()
method or bracket notation to check if a property exists.Each of these alternatives has its own trade-offs in terms of performance, readability, and maintainability.