<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
const limit = 10000000;
var array = [];
for (let i = 0; i < limit; i++) {
array.push(i);
}
function getRandomIndex() {
return Math.floor(Math.random() * array.length)
}
var element = array[getRandomIndex()];
array.find(x => x === element);
_.find(array, (x) => x === element);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Native | |
Lodash |
Test name | Executions per second |
---|---|
Native | 2.2 Ops/sec |
Lodash | 2.2 Ops/sec |
Let's dive into the details of this benchmark.
Benchmark Description
The benchmark compares the performance of two approaches for finding an element in an array: using native JavaScript (array.find()
) versus using the Lodash library (_.find()
).
Test Case 1: Native JavaScript (array.find())
In this test case, we use the native find()
method on the array. The benchmark script creates a large array of 10 million elements and pushes them to an array. A random index is then used to access an element in the array. The find()
method is called on the array with a callback function that checks if the current element matches the target element.
array.find(x => x === element);
Test Case 2: Lodash ( _.find() )
In this test case, we use the Lodash library's _.find()
method to find the element in the array. The benchmark script includes a reference to the Lodash library via a CDN URL.
_.find(array, (x) => x === element);
What is Lodash?
Lodash is a popular JavaScript utility library that provides a wide range of functions for tasks like array manipulation, object manipulation, string manipulation, and more. In this benchmark, we use the _.find()
method, which is similar to the native find()
method but with some additional features.
What are the pros/cons of these approaches?
Here are some key points:
Other Considerations
When deciding between these approaches:
Other Alternatives
If neither of these approaches suits your needs:
find()
is also available in the lodash.find
method.Now that we've gone through this detailed explanation, you should have a good understanding of what's being tested in this benchmark!