var obj = {
titlePlural:"red"
}
var obj2 ={
title:"red"
}
let title2 = obj2.titlePlural ? obj2.titlePlural : obj2.title
let title2 = obj2.titlePlural ||obj2.title
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Tertiary | |
Or |
Test name | Executions per second |
---|---|
Tertiary | 8685567.0 Ops/sec |
Or | 8225333.5 Ops/sec |
Let's break down the benchmark and explain what's being tested, compared, and considered.
Benchmark Overview
The benchmark is comparing two approaches to handling optional properties in JavaScript:
The test case uses a simple object with titlePlural
and title
properties. The goal is to determine which approach provides better performance.
Tertiary Approach
The Tertiary approach uses a ternary operator (?:
) to concisely express the conditional logic:
let title2 = obj2.titlePlural ? obj2.titlePlural : obj2.title;
This syntax is equivalent to a longer if-else statement:
if (obj2.titlePlural) {
title2 = obj2.titlePlural;
} else {
title2 = obj2.title;
}
Or Approach
The Or approach uses the logical OR operator (||
) to express the conditional logic:
let title2 = obj2.titlePlural || obj2.title;
This syntax is equivalent to a longer if-else statement:
if (obj2.titlePlural) {
title2 = obj2.titlePlural;
} else {
title2 = obj2.title;
}
Pros and Cons
Tertiary Approach:
Pros:
Cons:
?:
)Or Approach:
Pros:
Cons:
Other Considerations
When choosing between these approaches, consider the following factors:
Library Usage
There is no explicit library usage mentioned in the benchmark definition. However, some JavaScript engines (like V8) provide additional features or optimizations that might affect performance. In this case, it's likely that the differences are due to the specific JavaScript engine and its implementation of the ternary operator and logical OR operators.
Special JS Features
This benchmark does not use any special JavaScript features or syntax beyond what is commonly supported by most browsers. If you're interested in exploring more advanced features, consider looking into topics like async/await, Promises, or modern ES6+ features.