var map = new Map([
[0, "Initializing"],
[1, "Idle"],
[2, "Running"],
[3, "Stop"],
[4, "Error"],
]);
function switchCase(value) {
switch (value) {
case 0: return "Initializing";
case 1: return "Idle";
case 2: return "Running";
case 3: return "Stop";
case 4: return "Error";
default: return void 0;
}
}
function ifElse(value) {
if (value === 0) {
return "Initializing";
} else if (value === 1) {
return "Idle";
} else if (value === 2) {
return "Running";
} else if (value === 3) {
return "Stop";
} else if (value === 4) {
return "Error";
}
}
let value = map.get(0);
value = map.get(32);
value = map.get(1);
value = map.get(33);
value = map.get(2);
value = map.get(34);
value = map.get(3);
value = map.get(35);
value = map.get(4);
let value = switchCase(0);
value = switchCase(32);
value = switchCase(1);
value = switchCase(33);
value = switchCase(2);
value = switchCase(34);
value = switchCase(3);
value = switchCase(35);
value = switchCase(4);
let value = ifElse(0);
value = ifElse(32);
value = ifElse(1);
value = ifElse(33);
value = ifElse(2);
value = ifElse(34);
value = ifElse(3);
value = ifElse(35);
value = ifElse(4);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
map lookup | |
switch case | |
if/else |
Test name | Executions per second |
---|---|
map lookup | 204210800.0 Ops/sec |
switch case | 183550432.0 Ops/sec |
if/else | 209058560.0 Ops/sec |
Let's dive into the benchmark definition and test cases.
Benchmark Definition
The benchmark tests three approaches: map
lookup, switch case
, and if/else
. The script preparation code defines:
Map
data structure called map
with six key-value pairs.switchCase
: takes an integer value as input and returns a string based on the value using a switch
statement.ifElse
: takes an integer value as input and returns a string based on the value using multiple if-else
statements.The benchmark definition is written in JavaScript, which is the language used to execute the test cases.
Options Compared
The three approaches are compared in terms of their performance. Specifically, the benchmark measures:
Pros and Cons
Here's a brief summary of the pros and cons of each approach:
map
lookup:switch case
:if-else
chains for certain use cases.if-else
chain:map
lookup or switch case
, especially for large numbers of conditions.Library and Syntax
The test cases do not require any external libraries beyond JavaScript itself. The syntax used is standard JavaScript.
Special JS Features
None mentioned in the provided benchmark definition.
Alternatives
For comparison purposes, other approaches to achieve similar results could include:
for
loop with indexing: Instead of using a map
, you could use an array and iterate through its indices.Keep in mind that these alternatives would likely have different performance characteristics compared to the original map
-based approach.