<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
function get(obj, path, defaultValue) {
const keys = path.split(".");
let value = obj;
try {
for (key of keys) {
value = value[key];
}
return (typeof value === "undefined") ? defaultValue : value;
} catch (error) {
return defaultValue;
}
}
_.get({"a": {"b": {"c": {"d": {"e": 1} } } } }, "a.b.c.d.e", 0);
get({"a": {"b": {"c": {"d": {"e": 1} } } } }, "a.b.c.d.e", 0);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash | |
native |
Test name | Executions per second |
---|---|
lodash | 8101849.5 Ops/sec |
native | 6056691.5 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Description
The benchmark is comparing the performance of two approaches: using Lodash (a popular JavaScript utility library) and native JavaScript to access nested properties in an object.
Options Compared
There are two options being compared:
_.get()
function from Lodash, which provides a convenient way to access nested properties in objects.Pros and Cons of Each Approach
Lodash:
Pros:
Cons:
Native JavaScript:
Pros:
Cons:
Library: Lodash
Lodash is a popular JavaScript utility library that provides a wide range of functions for various tasks, including array manipulation, object manipulation, and more. The _.get()
function is specifically designed to access nested properties in objects. It takes three arguments: the object to search, the property path (a string or an array), and an optional default value.
Special JS Feature/ Syntax
None of the test cases use any special JavaScript features or syntax that would affect their interpretation.
Other Alternatives
If you want to compare performance between Lodash and native JavaScript approaches for accessing nested properties in objects, you could also consider using other libraries or frameworks that provide similar functionality, such as:
get()
function.In terms of native JavaScript alternatives, you could consider using recursive functions or iterative approaches to access nested properties in objects. For example:
function get(obj, path, defaultValue) {
const keys = path.split('.');
let value = obj;
for (let i = 0; i < keys.length; i++) {
if (!value[keys[i]]) break;
value = value[keys[i]];
}
return value === undefined ? defaultValue : value;
}
Keep in mind that these alternatives may require more boilerplate code and may not be as readable or maintainable as using a library like Lodash.