var animal = "dog"
function test(animal) {
switch(animal){
case 'cat': return 'Kitten'
case 'cattle': return 'Calf'
case 'cheetah': return 'Cub'
case 'dog': return 'Pup'
default: return "I don't know that"
}
}
console.log(test(animal))
function test(animal) {
var babyAnimal = {
cat:'Kitten',
cattle:'Calf',
cheetah:'Cub',
dog:'Pup'
}
return babyAnimal[animal] ?? "I don't know that"
}
console.log(test(animal))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Switch | |
Object Literal |
Test name | Executions per second |
---|---|
Switch | 47939.3 Ops/sec |
Object Literal | 43926.8 Ops/sec |
Let's break down the benchmark definition and results.
Benchmark Definition
The benchmark is called "Switch vs Object Literal - testing with simpler data". It consists of two test cases:
switch
statement to determine which baby animal to return based on the input animal
. The switch
statement checks the value of animal
and returns a corresponding string (e.g., "Kitten" for "cat").var babyAnimal = {...}
) to store mappings between animal names and their corresponding baby animals. It then looks up the value in the object using the input animal
as a key, returning the corresponding string (e.g., "Kitten" for "cat").Script Preparation Code
The script preparation code sets a variable animal
to the value "dog"
.
Test Cases
Each test case has two parts:
The benchmark definition code for each test case is as follows:
// Switch
function test(animal) {
switch(animal){
case 'cat': return 'Kitten'
case 'cattle': return 'Calf'
case 'cheetah': return 'Cub'
case 'dog': return 'Pup'
default: return "I don't know that"
}
}
// Object Literal
function test(animal) {
var babyAnimal = {
cat:'Kitten',
cattle:'Calf',
cheetah:'Cub',
dog:'Pup'
}
return babyAnimal[animal] ?? "I don't know that"
}
Latest Benchmark Result
The results show two test cases:
switch
statement has an execution speed of approximately 47,939 executions per second.Comparison and Analysis
The benchmark compares the performance of two approaches:
switch
statement that uses a series of if-else
statements under the hood.Pros and Cons:
Library Used
No external libraries are used in this benchmark.
JS Feature or Syntax
The test cases use JavaScript's switch
statement and object literals. The ??
operator (optional chaining) is also used in the object literal approach, which is a newer syntax introduced in ECMAScript 2020.
Alternatives
Other alternatives to consider:
if-else
statements.default
case: Adding a default case to the switch statement can improve performance by avoiding unnecessary checks.