<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js'></script>
var arr = [];
for (let i = 0; i < 10000; i++) {
arr.push({
id: i,
age: Math.random() * Math.floor(100)
});
}
!!arr && typeof arr === "array" && arr.find(({age}) => age < 70)
_.find(arr, ({age}) => age < 70)
arr.find(({age}) => age < 70)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Native find with check | |
Lodash find | |
Native find |
Test name | Executions per second |
---|---|
Native find with check | 7625951.0 Ops/sec |
Lodash find | 3101895.0 Ops/sec |
Native find | 14238797.0 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
Overview
The test compares three different approaches to finding an element in an array: native JavaScript find()
method, Lodash's find()
function, and a native implementation with an additional check.
Native find()
The first approach uses the built-in find()
method of JavaScript arrays. This method returns the first element in the array that satisfies the provided condition. In this case, the condition is age < 70
.
Pros:
Cons:
!!arr && typeof arr === "array"
), which might incur some overhead due to the extra verification.Lodash find()
The second approach uses Lodash's find()
function. This is a popular utility library for functional programming in JavaScript.
Pros:
Cons:
Native find() with check
The third approach is similar to the first one but adds an additional check (!!arr && typeof arr === "array"
). This test case is used to ensure that the native find()
method behaves correctly even when the array might be null or undefined.
Pros:
Cons:
Library: Lodash
Lodash is a popular JavaScript utility library that provides a wide range of functions for functional programming, data manipulation, and more. In this case, the find()
function is used to perform array operations. Lodash is often used in conjunction with other libraries or frameworks to provide additional functionality.
Other alternatives
If you were to reimplement the benchmark without using Lodash, you could consider the following alternatives:
find()
method using loops and conditional statements.some()
, every()
, or forEach()
instead of find()
.Keep in mind that these alternatives would likely require more code and might not be as efficient as the native implementation.