<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.core.js"></script>
var users = {
'id1': { 'user': 'joey', 'age': 32 },
'id2': { 'user': 'ross', 'age': 41 },
'id3': { 'user': 'chandler', 'age': 39 },
'id4': { 'user': 'joey', 'age': 32 },
'id5': { 'user': 'ross', 'age': 41 },
'id6': { 'user': 'chandler', 'age': 39 },
'idNull':null,
'id7': { 'user': 'joey', 'age': 32 },
'id8': { 'user': 'ross', 'age': 41 },
'id9': { 'user': 'chandler', 'age': 39 },
'id10': { 'user': 'joey', 'age': 32 },
'id11': { 'user': 'ross', 'age': 41 },
'id12': { 'user': 'chandler', 'age': 39 }
};
// Native
Object.values(users).find(function (o) { return o.age < 40; })
_.find(users, function (o) { return o.age < 40; })
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array find | |
_.find |
Test name | Executions per second |
---|---|
array find | 4233395.0 Ops/sec |
_.find | 3818025.5 Ops/sec |
Let's break down the provided JSON and explain what is tested, compared, and their pros and cons.
Benchmark Definition JSON
The benchmark consists of two test cases:
Object.values()
and Array.prototype.find()
methods to find an object with a specific property (age < 40
) in the users
object._find()
method, to achieve the same result as the native find()
method.Comparison
The comparison between these two approaches is primarily about performance and readability. The native Object.values()
and Array.prototype.find()
methods are compared with Lodash's _find()
method.
Pros and Cons
Native find:
Pros:
Cons:
Lodash _.find:
Pros:
Cons:
Library: Lodash
Lodash is a popular JavaScript utility library developed by Isaac Schlueter in 2012. It provides a wide range of high-quality functions for tasks such as array manipulation, object transformation, and functional programming. The _find()
method is one of the core functions in Lodash, designed to find the first element in an array that satisfies a provided predicate function.
Special JS Feature/Syntax: None
There are no special JavaScript features or syntax used in these test cases.
Other Alternatives
For those interested in exploring alternative approaches, here are some other methods you can use:
users
object and find the desired result.for (var i = 0; i < Object.keys(users).length; i++) {
if (users[Object.keys(users)[i]].age < 40) {
// Result found!
}
}
filter()
: Utilize the Array.prototype.filter()
method to find objects that satisfy the condition.var result = Object.values(users).filter(function (o) { return o.age < 40; });
These alternatives may not be as efficient or readable as the native methods and Lodash's implementation, but they demonstrate alternative ways to achieve the same result.