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 |
This benchmark tests the performance of two different ways to determine the baby name for an animal: using a switch
statement or an object literal.
Options Compared:
switch
statement: This is a traditional control flow mechanism that evaluates an expression and compares it to a series of case
values. If a match is found, the corresponding code block is executed.Pros and Cons:
switch
:
case
statements grows. Performance can be slightly worse than object literals in some scenarios.Object Literal:
switch
statements, especially with many cases.Alternatives:
Other alternatives to consider:
Additional Considerations:
This benchmark measures execution speed, but other factors might influence your choice:
Let me know if you have any more questions.