<script src="https://cdn.jsdelivr.net/lodash/4.16.0/lodash.min.js"></script>
var person = {name: 'Frederick', lastName: 'Corcino Alejo', nested: {name: 'test'}};
function safeGet(obj, path, defaultValue) {
return path.split('.').reduce((xs, x) => (xs && xs[x]) ? xs[x] : defaultValue, obj);
}
_.get(person, 'name', '');
_.get(person, 'nested.name', '');
safeGet(person, 'name', '');
safeGet(person, 'nested.name', '');
person?.name ?? '';
person?.nested?.name ?? '';
person?.name || '';
person?.nested?.name || '';
person.name;
person.nested.name;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash get | |
safeGet | |
Null operator | |
Or Operator | |
Direct |
Test name | Executions per second |
---|---|
Lodash get | 3904029.2 Ops/sec |
safeGet | 5681454.0 Ops/sec |
Null operator | 17298478.0 Ops/sec |
Or Operator | 17397892.0 Ops/sec |
Direct | 17467270.0 Ops/sec |
The benchmark provided is a performance comparison between different methods to safely access properties in a JavaScript object. The core of the test is to evaluate several approaches for getting nested properties from an object, specifically testing:
_.get
- A utility function from the Lodash library.safeGet
- A custom implementation.??
) - A modern JavaScript feature.||
) - A traditional approach.Lodash's _.get
:
Custom safeGet
:
Nullish Coalescing Operator (??
):
null
or undefined
.0
or ''
) may need to be handled.Logical OR Operator (||
):
0
, ''
) since they will return the default value.Direct Property Access:
The benchmark results show the "Executions Per Second" for each method, highlighting that the fastest methods were Direct Property Access and the Null Operator, both benefiting from their straightforward access strategies. Meanwhile, the methods using Lodash and the custom safeGet
were significantly slower due to the additional complexity inherent in both approaches.
Other alternatives that could be considered for accessing properties safely include:
Optional Chaining (?.
): Similar to the tested null operator, it can help in safely accessing nested properties and can be combined with the nullish coalescing operator for safe defaults.
TypeScript's Type Safety: Using strong typing can help avoid accessing undefined properties at runtime, although this may not reflect directly in performance benchmarks.
Use of Proxy objects: A more advanced JavaScript feature that can define custom behaviors for fundamental operations (e.g., property access), but with added complexity.
Overall, the test case effectively showcases the performance differences between different methodologies for property access in JavaScript, providing insights pertinent to software engineers when choosing which approach to utilize based on the requirements for safety, performance, and dependency management.