var obj = {a: {b: {c: {d: 1}}}}
var badObj = {}
(obj.a == null ? undefined : obj.a.b == null ? undefined : obj.a.b.c == null ? undefined : obj.a.b.c.d) || 2
(badObj.a == null ? undefined : badObj.a.b == null ? undefined : badObj.a.b.c == null ? undefined : badObj.a.b.c.d) || 2
_.get(obj, "a.b.c.d", 2)
_.get(badObj, "a.b.c.d", 2)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Optional Chaining | |
Lodash |
Test name | Executions per second |
---|---|
Optional Chaining | 117776872.0 Ops/sec |
Lodash | 5019099.0 Ops/sec |
Let's break down the provided benchmark and explain what is being tested, compared, and their pros and cons.
Benchmark Definition
The benchmark is testing two approaches to accessing nested properties of objects:
Options Compared
The benchmark compares two options:
Pros and Cons
Optional Chaining
Pros:
Cons:
Lodash _.get() function
Pros:
Cons:
Library: Lodash
Lodash is a popular JavaScript utility library that provides various functions for common tasks, such as data manipulation, string manipulation, and functional programming utilities. The _.get() function is part of this library, which allows you to safely access nested properties of objects while providing a default value.
Special JS Feature or Syntax: None
There are no special JavaScript features or syntaxes being used in this benchmark beyond the Optional Chaining feature introduced in ES12.
Other Alternatives
If you want to compare alternative approaches to accessing nested properties, here are a few options:
obj.a.b.c.d
) instead of Optional Chaining.function getValue(obj) { return obj.a && obj.a.b && obj.a.b.c && obj.a.b.c.d; }
Keep in mind that these alternatives may have different performance characteristics and code readability trade-offs compared to Optional Chaining and Lodash _.get().