<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js" type="text/javascript"></script>
<script src="https://cdn.rawgit.com/mariocasciaro/object-path/master/index.js"></script>
var obj = {
stuff: {
things: {
stuff: 'things',
things: 'stuff',
other: {
stuff: 'things'
}
}
}
};
_.get(obj, 'stuff.things.other.stuff');
objectPath.get(obj, 'stuff.things.other.stuff');
obj.stuff && obj.stuff.things && obj.stuff.things.other && obj.stuff.things.other.stuff;
obj.stuff?.things?.other?.stuff;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash get | |
object path | |
Native | |
Optional chaining |
Test name | Executions per second |
---|---|
Lodash get | 2240780.5 Ops/sec |
object path | 996849.2 Ops/sec |
Native | 3179911.5 Ops/sec |
Optional chaining | 12580500.0 Ops/sec |
Let's break down what is being tested in the provided JSON.
Benchmark Definition
The benchmark defines four test cases to compare the performance of different approaches:
_.get
method from Lodash, a popular JavaScript utility library.objectPath.get
method from object-path, another JavaScript utility library.?.
) to access nested properties.?.
operator to access nested properties.Options compared
The benchmark compares the performance of these four approaches in accessing a deeply nested object property. The test cases use different methods to navigate the object:
?.
) to access the property directly.?.
operator to access the property.Pros and Cons
Here's a brief summary of each approach:
Library explanations
Special JS features or syntax
The benchmark uses the ?.
operator, which is a new feature introduced in ECMAScript 2020 (ES10). The ?.
operator allows safe navigation through nested properties, returning undefined
if any of the preceding expressions are falsy. This feature is widely supported in modern browsers and JavaScript engines.
Other alternatives
If you need to compare performance with other approaches, here are some additional options:
foo.bar()
or baz.foo()
instead of Lodash's _get
method or object-path's get
method.