<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js'></script>
var users = [
{ 'user': 'joey', 'age': 28 },
{ 'user': 'ross', 'age': 31 },
{ 'user': 'chandler', 'age': 30 },
{ 'user': 'jessika', 'age': 21 },
{ 'user': 'amanda', 'age': 17 }
]
let index = users.findIndex((u, idx) => {if (idx < 2) return false; return u.age === 30})
let user = users[index]
let index = _.findIndex(users, u => u.age === 30, 2)
let user = users[index]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Native findIndex | |
_.findIndex |
Test name | Executions per second |
---|---|
Native findIndex | 6617068.0 Ops/sec |
_.findIndex | 3091733.2 Ops/sec |
Let's break down the provided JSON and explain what's being tested, along with the pros and cons of each approach.
Benchmark Overview
The benchmark compares the performance of three approaches:
findIndex
methodfindIndex
functionfind
functionAll three tests aim to find an element in a given array (users
) based on its age property, but with some differences in their implementation.
Native JavaScript findIndex
Method
The native findIndex
method is used to search for the first index at which a specified value occurs in the array. In this test case, it's used to find an element with age === 30
.
Pros:
Cons:
Lodash findIndex
Function
The Lodash findIndex
function is a wrapper around the native findIndex
method, but with some additional features and optimizations. In this test case, it's used to find an element in the users
array based on its age property, starting from index 2.
Pros:
findIndex
due to Lodash's optimizationCons:
Lodash find
Function
The Lodash find
function is another wrapper around the native Array.prototype.find()
method. In this test case, it's used to find an element in the users
array based on its age property.
Pros:
findIndex
Cons:
Library Explanation
In this benchmark, two libraries are used:
Other Considerations
When choosing between these approaches, consider the following factors:
findIndex
may be faster, but optimized library implementations can provide similar performance benefits.findIndex
might be a better choice.Alternatives
If you're not interested in using external libraries like Lodash, you can explore other alternatives:
Array.prototype.find()
method: Similar to native findIndex
, but for finding the first element matching a condition.In summary, this benchmark compares the performance of three approaches: native JavaScript findIndex
, Lodash findIndex
, and Lodash find
. Each approach has its pros and cons, and choosing the right one depends on your specific requirements and preferences.