var obj = {a: {b: {c: {d: 1}}}}
obj.a && obj.a.b && obj.a.b.c && obj.a.b.c.d
_.get(obj, "a.b.c.d")
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Native | |
Lodash |
Test name | Executions per second |
---|---|
Native | 3593676.2 Ops/sec |
Lodash | 2059543.6 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and their pros/cons.
What is being tested?
The benchmark compares two approaches to access nested properties in an object:
?.
operator. For example: obj.a && obj.a.b && obj.a.b.c && obj.a.b.c.d
.Options compared
The benchmark compares the performance of these two approaches:
Pros and Cons:
Library:
In this benchmark, the Lodash library is being tested. _.get() is a utility function that takes an object and a path string as arguments, returning the value at the specified path in the object. Its purpose is to provide a flexible way to access nested properties without having to manually chain dot notation.
Special JS feature or syntax:
The benchmark uses ES12's Optional Chaining (?.
) feature, which allows you to safely navigate nested objects and avoid null pointer exceptions.
Other alternatives:
If the _.get() function is not an option, other alternatives for accessing nested properties include:
obj.a.b.c.d
)obj['a']['b']['c']['d']
)Keep in mind that these alternatives might have different performance characteristics, readability, and maintainability trade-offs compared to the native Optional Chaining feature.