var obj = {a: {b: {c: {d: 1}}}}
obj.a == null ? undefined : obj.a.b == null ? undefined : obj.a.b.c == null ? undefined : obj.a.b.c.d
_.get(obj, "a.b.c.d")
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Optional Chaining | |
Lodash |
Test name | Executions per second |
---|---|
Optional Chaining | 4232619.5 Ops/sec |
Lodash | 2579456.8 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark is comparing the performance of two approaches to access nested properties in an object: Optional Chaining
(using the ?.
syntax) versus using the _get
method from the Lodash library.
What's Being Tested?
The test cases are designed to measure the execution time of accessing nested properties in the following scenarios:
obj.a == null ? undefined : ...
)obj.a.b == null ? undefined : ...
)The two approaches being compared are:
Option 1: Optional Chaining
Using the ?.
syntax to access nested properties, like this:
const result = obj.a?.b?.c?.d;
This approach checks if each property exists before attempting to access it. If any of the properties do not exist, the expression will return undefined
.
Option 2: Lodash _.get
Using the _get
method from the Lodash library to access nested properties, like this:
const result = _.get(obj, "a.b.c.d");
This approach takes an object and a string representing the property path as arguments. It will return undefined
if any of the properties in the path do not exist.
Pros and Cons
Optional Chaining:
Pros:
Cons:
Lodash _.get:
Pros:
Cons:
Library: Lodash
The _get
method is part of the Lodash library, a popular utility library for JavaScript. The purpose of Lodash is to provide a set of helper functions that make common programming tasks easier.
Special JS Feature/Syntax
None are mentioned in this benchmark, so we won't delve into any special features or syntaxes.
Alternatives
Other alternatives for accessing nested properties include:
in
operator and conditional statementsHowever, these approaches may be less efficient and more error-prone than the two methods being compared.
I hope this explanation helps you understand what's being tested in this benchmark!