<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
Object.byString = function(o, s) {
s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
s = s.replace(/^\./, ''); // strip a leading dot
var a = s.split('.');
for (var i = 0, n = a.length; i < n; ++i) {
var k = a[i];
if (k in o) {
o = o[k];
} else {
return;
}
}
return o;
}
Object.byString({
a: 1
}, 'a');
_.get({a: 1}, "a")
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Case 1 | |
lodash |
Test name | Executions per second |
---|---|
Case 1 | 5868944.0 Ops/sec |
lodash | 14108421.0 Ops/sec |
I'll explain the provided JSON benchmark definition and its options.
Benchmark Definition
The benchmark measures the performance of two approaches to retrieve an object value by path: Object.byString
(custom implementation) and lodash.get
.
Options Compared
Object.byString
):get
function:Other Considerations
lodash
library is used in the second test case (_.get
function). Lodash is a popular utility library for functional programming and data manipulation.Alternative Approaches
If you're interested in exploring alternative approaches, consider the following:
in
operator with bracket notation: o[k]
Object.byString
: e.g., function get(o, k) { if (k in o) return o[k]; else if (typeof o === 'object') return Object.keys(o).map(k => get(o[k], k)).find(v => v !== undefined); }
fast-leveldb
or lodash.cache
to optimize object lookups.Keep in mind that these alternative approaches may have different performance characteristics and trade-offs compared to the custom implementation and Lodash get
function.