const input = 1;
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 = 1;
const LUT = {
0: true,
1: true,
2: true,
3: true,
4: true,
5: true,
6: true,
7: true,
8: true,
9: true,
10: true
}
LUT[input];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Switch | |
Map |
Test name | Executions per second |
---|---|
Switch | 127591672.0 Ops/sec |
Map | 135103376.0 Ops/sec |
The benchmark conducted on the MeasureThat.net platform compares two different approaches for determining the value of an input based on predefined conditions: using a switch
statement and using a lookup table (often referred to as a "map"). Here's a breakdown of what is being tested, the pros and cons of each approach, and alternative options:
Switch Statement:
switch
statement with multiple cases. Here, if input
equals a certain number (1 through 10), the function returns true
. The switch case will evaluate each case until it finds a match or reaches the end.Pros:
Cons:
Lookup Table (Map):
true
in this case) are accessed directly using the input as a key.Pros:
Cons:
From the benchmark results:
switch
approach executed 164,259,088 times per second.map
approach executed 155,001,488 times per second.In this specific case, the switch
statement performed slightly better than the lookup table in terms of raw execution speed. This finding could vary with different inputs or larger cases.
lodash
for utility functions, which can simplify certain mapping scenarios but may introduce additional overhead.In summary, while both methods achieve the same end result, the decision on which to use should account for performance, clarity, maintainability, and contextual needs.