window.map = {
"first": "1",
"second": "2",
"third": "3",
"forth": "4",
"fifth": "5",
"sixth": "6",
"seventh": "7",
"eighth": "8",
"nineth": "9",
"tenth": 10
};
window.values = ["first", "second", "third", "forth", "fifth", "sixth", "seventh", "eighth", "nineth", "tenth"];
const { map, values } = window;
function resolve(value) {
switch (value) {
case "first":
return "1";
case "second":
return "2";
case "third":
return "3";
case "forth":
return "4";
case "five":
return "5";
case "sixth":
return "6";
case "seventh":
return "7";
case "eighth":
return "8";
case "nineth":
return "9";
case "tenth":
return "10";
}
}
for (let i=0; i < values.length; i++) {
resolve(values[i]);
}
const { map, values } = window;
function resolve(value) {
return map[value];
}
for (let i=0; i < values.length; i++) {
resolve(values[i]);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Switch Case | |
Map |
Test name | Executions per second |
---|---|
Switch Case | 11187048.0 Ops/sec |
Map | 6873633.5 Ops/sec |
Let's break down what's being tested in this benchmark.
Benchmark Goal
The goal of this benchmark is to compare the performance of two approaches: using a switch-case
statement and using an object (specifically, a map
) to look up values.
What is being tested?
In both test cases:
resolve(value)
is defined.values
).resolve(value)
function uses a switch-case
statement to look up the value and return a corresponding string.resolve(value)
function looks up the value in an object (predefined as window.map
) using the syntax map[value]
.Options compared
The two options being compared are:
if-else
chain to look up values and returns a corresponding string.window.map
) with keys matching the expected values, and looks up the value using the syntax map[value]
.Pros and Cons of each approach
switch
statement, and may not scale well for larger numbers of values.Library and purpose
In this benchmark, window.map
is used as an object with predefined keys. This object is not part of any specific JavaScript library, but rather a simple data structure used for demonstration purposes.
Special JS feature or syntax
This benchmark does not use any special JavaScript features or syntax that would be unfamiliar to most developers.
Other alternatives
If you were looking for alternative approaches to this benchmark, some options might include:
call()
method to look up valuesHowever, these alternatives are not being tested in this specific benchmark.