<!--your preparation HTML code goes here-->
/*your preparation JavaScript code goes here
To execute async code during the script preparation, wrap it as function globalMeasureThatScriptPrepareFunction, example:*/
async function globalMeasureThatScriptPrepareFunction() {
// This function is optional, feel free to remove it.
// await someThing();
}
const myObj = {}
const myFunc = (param) => param?.key?.nestedKey ?? []
for (let i = 0; i < 1e6; i++) {
myFunc(myObj)
}
const myObj = {}
const myFunc = (param) => {
if (!param.key) return []
if (!param.key.nestedKey) return []
return param.key
}
for (let i = 0; i < 1e6; i++) {
myFunc(myObj)
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
nullish | |
if |
Test name | Executions per second |
---|---|
nullish | 472.7 Ops/sec |
if | 489.5 Ops/sec |
This benchmark compares two approaches for safely accessing nested properties in a JavaScript object and handling the case where the properties might be undefined or nonexistent. Specifically, it evaluates the use of the nullish coalescing operator (??
) combined with optional chaining (?.
), versus traditional conditional statements in an if
structure to achieve similar functionality.
Nullish Coalescing with Optional Chaining (nullish
Test)
const myObj = {};
const myFunc = (param) => param?.key?.nestedKey ?? [];
for (let i = 0; i < 1e6; i++) {
myFunc(myObj);
}
?.
), which allows for safe access to nested properties. If any part of the chain returns undefined
or null
, the evaluation short-circuits and ends, returning undefined
. The nullish coalescing operator (??
) then provides a fallback value of an empty array []
if the entire expression yields undefined
.Traditional If-Else Conditional (if
Test)
const myObj = {};
const myFunc = (param) => {
if (!param.key) return [];
if (!param.key.nestedKey) return [];
return param.key;
};
for (let i = 0; i < 1e6; i++) {
myFunc(myObj);
}
if
statements to check each level of the object's nested properties manually. If any of the conditions fail, it returns an empty array.if
test had 489.52 executions per second.nullish
test recorded 472.68 executions per second.Both methods performed similarly, although the if
construct showed a marginally better execution rate in this test. However, the slight difference in execution speed may not justify opting for verbosity over conciseness in most scenarios.
Choosing between these approaches can depend on the context and preferences. Here are some considerations:
Readability vs. Performance: In scenarios where code maintainability and clarity are prioritized, the nullish coalescing with optional chaining may be preferred despite being slightly slower. This is especially true for teams working with varying levels of JavaScript expertise.
Legacy Browser Support: It's also important to note that optional chaining and nullish coalescing are features introduced in ES2020. If the targeted execution environment does not support these features (e.g., older browsers or JavaScript engines), the if-else structure may be a requirement.
Error Handling: The traditional method allows for more complex scenarios where logging or specific error handling might be necessary. Conversely, optional chaining may not give the developer much insight into where the access failed.
Other Alternatives: In addition to these methods, there are libraries such as Lodash that provide utility functions like _.get()
for safely accessing deeply nested properties without additional boilerplate, offering both safety and conciseness.
In conclusion, both the nullish coalescing with optional chaining method and the traditional if-else method have valid use cases, and the choice between them may depend on team standards, project requirements, and considerations about readability versus performance.