var runSwitch = input => {
switch(input) {
case 'one':
return true;
case 'two':
return true;
case 'three':
return true;
case 'four':
return true;
case 'five':
return true;
case 'six':
return true;
case 'seven':
return true;
case 'eight':
return true;
case 'nine':
return true;
case 'ten':
return true;
}
}
var LUT = {
zero: true,
one: true,
two: true,
three: true,
four: true,
five: true,
six: true,
seven: true,
eight: true,
nine: true,
ten: true
}
var input = 'one';
runSwitch(input);
LUT[input];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Switch | |
Map |
Test name | Executions per second |
---|---|
Switch | 8119621.5 Ops/sec |
Map | 8822216.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition
The benchmark is designed to compare two approaches: switch
statements and using an object map (LUT
) with early exit conditions. The test case uses a simple scenario where it takes an input string and checks if it matches one of 10 predefined values.
Options Compared
switch
statement. This approach is straightforward but can be slower due to the overhead of branching instructions.LUT
) with early exit conditions. This approach takes advantage of JavaScript's hash table implementation and can be faster than a traditional switch
statement.Pros and Cons
Library and Its Purpose
The LUT
(Lookup Table) object is used to store the precomputed results for each input value. This allows for fast lookups using the object's hash table implementation. The purpose of this library is to provide a way to speed up the comparison process by reducing the number of branching instructions.
Special JS Feature or Syntax There are no special JavaScript features or syntax used in this benchmark.
Other Alternatives
indexOf()
or includes()
methods could be another alternative to compare performance. However, this approach would require creating an array with all possible values, which might be cumbersome if the number of cases is large.In summary, the benchmark compares two approaches: traditional switch
statements and using an object map (LUT
) with early exit conditions. The LUT
approach takes advantage of JavaScript's hash table implementation for faster lookups but requires a predefined object with all possible values.