<script src='https://cdn.jsdelivr.net/npm/lodash@4.17.13/lodash.min.js'></script>
var data = {
id: 1,
a: 1,
b: '',
c: '',
d: false,
e: '',
f: 1,
g: {
h: 1,
i: 'Dannag'
},
k: 1,
l: 1,
}
_.get(data, 'g.i');
const get = (o, path) => path.split('.').reduce((o = {}, key) => o[key], o);
get(data, 'g.i')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash get | |
Native code |
Test name | Executions per second |
---|---|
Lodash get | 2602701.2 Ops/sec |
Native code | 4512734.5 Ops/sec |
Let's break down the benchmark and analyze what's being tested.
Benchmark Overview
The benchmark is designed to compare the performance of two approaches: using the lodash
library's get
function and implementing a custom native code solution. The goal is to measure which approach is faster.
Library: Lodash
Lodash is a popular JavaScript utility library that provides various functions for tasks such as string manipulation, array manipulation, and more. In this benchmark, lodash.get
is used to access nested properties in an object. The get
function takes two arguments: the object to access (o
) and the path to the desired property (e.g., 'g.i'
). It returns the value of the property at that path if it exists.
Custom Native Code Solution
The second approach is implemented using a simple recursive function in JavaScript:
const get = (o, path) => {
const keys = path.split('.').reduce((acc, key) => [...acc, key], []);
return keys.reduce((o = {}, key) => o[key] ? o[key] : null, o);
};
This function takes the object o
and the path path
as input. It splits the path into individual keys using the dot (.
) character and then recursively traverses the object to find the value at that path.
Comparison of Approaches
Here are some pros and cons of each approach:
get
FunctionOther Considerations
There are no specific JavaScript features or syntax mentioned in this benchmark. However, it's worth noting that some modern JavaScript features like let
and const
declarations may not have a significant impact on performance compared to traditional variable declaration using var
.
Some alternatives to the custom native code solution could include:
in
operator to access nested properties:const get = (o, path) => {
for (let key of path.split('.')) {
if (key in o) {
return o[key];
}
}
};
fast-get
which provides an optimized implementation of the get
function.It's worth noting that these alternatives may not necessarily outperform the custom native code solution, and the optimal approach depends on the specific use case and performance requirements.
In summary, the benchmark is designed to compare the performance of two approaches: using lodash.get
and implementing a custom native code solution. The pros and cons of each approach are discussed, and some alternative solutions are mentioned for consideration.