<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var obj = {a:{c:1},b:[{v:3},{f:2}]};
let a = 0;
if(obj && obj.b && obj.b[0]){
a = obj.b[0].v;
}
let a = _.get(obj,"b[0].v",null);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Native | |
Lodash |
Test name | Executions per second |
---|---|
Native | 2050732.0 Ops/sec |
Lodash | 1189315.4 Ops/sec |
Let's break down the benchmark and explain what's being tested.
What is being tested?
The benchmark compares two ways of retrieving a property from an object using JavaScript:
obj && obj.b && obj.b[0]
syntax to check if the object exists and has a property at index 0, and then accessing that property._get
function from Lodash library to safely retrieve the property.Options compared
The two options being compared are:
obj && obj.b && obj.b[0]
_get(obj, "b[0].v", null)
Pros and Cons of each approach:
Lodash library
The Lodash library provides various utility functions for functional programming and data manipulation. In this case, _get
is a function that safely retrieves a value from an object by providing a default value if the property does not exist.
Special JS feature or syntax
There isn't any specific JavaScript feature or syntax mentioned in this benchmark. However, it's worth noting that the let a = 0;
line declares a variable a
with an initial value of 0, which is a common practice in JavaScript.
Other alternatives
If you wanted to test other ways of retrieving properties from objects, some alternative approaches could be:
obj["b[0].v"]
) instead of dot notation or safe functions like _get
.Keep in mind that these alternatives would change the benchmark's focus and results, so it's essential to choose the approach that best represents your use case.