animal = "cheetah"
const babyAnimals = {
dog: "Puppy",
cat: "Kitten",
cheetah: "Cub",
};
let result1 = babyAnimals[animal] || "-";
let result2 = "-";
if (animal === "dog") result2 = "Puppy";
else if (animal === "cat") result2 = "Kitten";
else if (animal === "cheetah") result2 = "Cub";
let result3 = "-";
switch (animal) {
case "dog":
result3 = "Puppy";
break;
case "cat":
result3 = "Kitten";
break;
case "cheetah":
result3 = "Cub";
break;
default:
}
const babyAnimals = {
dog: "Puppy",
cat: "Kitten",
cheetah: "Cub",
};
let result1 = babyAnimals[animal] ?? "-";
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object Literal | |
If Else | |
Switch Case | |
Object Literal 2 |
Test name | Executions per second |
---|---|
Object Literal | 4592487.0 Ops/sec |
If Else | 1571642.4 Ops/sec |
Switch Case | 4694115.5 Ops/sec |
Object Literal 2 | 4718195.0 Ops/sec |
Let's dive into the world of JavaScript benchmarks.
Benchmark Overview
The provided benchmark compares three different approaches to retrieve values from an object: Object Literal, If-Else statement, and Switch Case statement. The benchmark uses a simple scenario where it checks if a specific animal (e.g., "cheetah") exists in an object containing various animals (dog, cat, cheetah) as keys.
Options Compared
Pros and Cons
Other Considerations
??
operator (introduced in ECMAScript 2017) is used as a safer alternative to object literal access. It returns the first operand if it's truthy, and the second operand if it's falsy.||
operator is used to provide a default value when the specified animal is not found in the object.Library Usage
The benchmark does not explicitly use any libraries. However, it relies on the JavaScript engine's built-in features, such as object literals, if-else statements, and switch case statements.
Special JS Features/Syntax
None mentioned in this specific benchmark.
Benchmark Results
The latest benchmark results show that:
??
operator) has the highest executions per second (4718195.0), indicating it's the most efficient approach.Keep in mind that these results might vary depending on the specific JavaScript engine and platform used.
Alternatives
For similar benchmarks, you can explore other scenarios, such as: