<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.b.c?.d ?? 2
_.get(obj, "a.b.c.d", 2)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
optional | |
lodash |
Test name | Executions per second |
---|---|
optional | 7132112.0 Ops/sec |
lodash | 1004431.5 Ops/sec |
Let's break down the provided benchmark definition and test cases.
What is tested?
The provided benchmark measures the performance difference between two approaches: Optional Chaining (obj.a.b.c?.d
) and Lodash's _.get()
function.
Options compared:
There are two options being compared:
_.get()
function: Lodash is a popular utility library for JavaScript that provides various functions, including _.get()
, which achieves similar functionality to Optional Chaining.Pros and Cons:
_.get()
function:Library and purpose:
The library used in this benchmark is Lodash. Its purpose is to provide utility functions that can be used across various JavaScript applications.
Special JS feature or syntax:
There are no special features or syntax mentioned in the provided benchmark definition.
Other alternatives:
Alternative approaches for nested property access include:
obj["a"]["b"]["c"]["d"]
obj["a.b.c.d"]
(Note: This is not as concise as Optional Chaining or Lodash's _.get()
function.)in
operator to check for existence and then accessing the property.These alternatives may have different performance characteristics, trade-offs, and browser support depending on their implementation.
Benchmark preparation code:
The provided Script Preparation Code sets up two objects:
obj
: a nested object with properties a
, b
, c
, and d
.badObj
: an empty object to be used for testing errors in older browsers.The HTML Preparation Code includes the Lodash library, which is required for the benchmark.