function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
let x= "";
const i = getRandomInt(6);
switch(i) {
case 0: x= "Zero"; break;
case 1: x= "One"; break;
case 2: x= "Two"; break;
case 3: x= "Three"; break;
case 4: x= "Four"; break;
case 5: x= "Five"; break;
}
let x = "";
const i = getRandomInt(6);
if (i === 0) x = "Zero"
else if (i === 1) x = "One"
else if (i === 2) x = "Two"
else if (i === 3) x = "Three"
else if (i === 4) x = "Four"
else if (i === 5) x = "Five"
let x = "";
const i = getRandomInt(6);
x = {
0: "Zero",
1: "One",
2: "Two",
3: "Three",
4: "Four",
5: "Five",
}[i];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Switch | |
If (else) | |
Object selector |
Test name | Executions per second |
---|---|
Switch | 1255065.9 Ops/sec |
If (else) | 1271773.8 Ops/sec |
Object selector | 1280706.1 Ops/sec |
Let's break down what's being tested in this benchmark.
Benchmark Definition
The benchmark is designed to compare the performance of three different approaches: switch
statement, if-else
statement, and object selector (also known as a hash table lookup).
Options Compared
switch
statement uses a value to determine which code block to execute. In this case, it's used to assign a string value to variable x
based on the random integer i
.if-else
statement checks if a condition is true and executes one branch if true and another branch if false. Here, it's used in an equivalent way to the switch
statement.x
based on the random integer i
.Pros and Cons of Each Approach
switch
switch
if the number of possible values is smallLibrary and Special JS Feature
There doesn't appear to be any specific library used in this benchmark. However, it's worth noting that modern JavaScript engines have various optimizations and features that can affect performance, such as:
Other Alternatives
If you're looking for alternative approaches or want to explore more performance-optimized options, consider:
i
value and use it directly.Keep in mind that these alternatives may introduce additional complexity, require more memory, or have different performance characteristics compared to the original switch
, if-else
, and object selector approaches.