<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
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)
obj?.a?.b?.c?.d || 2
badObj?.a?.b?.c?.d || 2
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Optional Chaining | |
Lodash | |
actual optional chaining |
Test name | Executions per second |
---|---|
Optional Chaining | 6685353.5 Ops/sec |
Lodash | 2521212.8 Ops/sec |
actual optional chaining | 13004770.0 Ops/sec |
What is tested on the provided JSON?
The provided JSON represents a JavaScript benchmark test case that compares the performance of three approaches:
==
operator.?.
operator.Options compared:
The benchmark compares the performance of each approach on a specific test case:
obj.a.b.c.d
).obj?.a?.b?.c?.d
) and also includes null checks using || 2
.Pros and cons of each approach:
Library used:
The benchmark uses Lodash version 4.17.5 for its _.get() function.
Special JS feature or syntax:
The benchmark takes advantage of the new optional chaining feature introduced in ECMAScript 2020, which allows for more expressive and safe navigation through nested objects using the ?.
operator. This syntax is only available in modern browsers that support ECMAScript 2020.
Other considerations:
Other alternatives:
If you're looking for alternative approaches to achieve similar results without using optional chaining or Lodash's _.get() function, you could explore:
obj.a && obj.a.b && ...
)However, these alternatives may introduce additional complexity, overhead, or performance trade-offs compared to the original approaches used in this benchmark.