const arr = Array.from({ length: 20000 }, (_, i) => ({ property: i }))
const elementToFind = 15000;
const element = arr.find((el) => el.property === elementToFind);
const arr = Array.from({ length: 20000 }, (_, i) => ({ property: i }))
const elementToFind = 15000;
let element = undefined;
for (let i = 0; i < arr.length; i++) {
if (arr[i].property === elementToFind) {
element = arr[i];
break;
}
}
const arr = Array.from({ length: 20000 }, (_, i) => ({ property: i }))
const elementToFind = 15000;
let element = undefined;
let i = 0;
while(element === undefined) {
if(arr[i].property === elementToFind) {
element = elementToFind;
}
i++;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
find | |
For-loop | |
while |
Test name | Executions per second |
---|---|
find | 598.5 Ops/sec |
For-loop | 634.3 Ops/sec |
while | 255.8 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
What is being tested?
The provided benchmark tests three approaches to find an element in an array: find
, for-loop
, and while
. The test case uses 20,000 elements in the array, generated using the Array.from
method. The goal is to determine which approach performs better in terms of execution speed.
Options compared
The benchmark compares three options:
find
method, which returns the first element that satisfies the provided condition.Pros and Cons of each approach
find
method.find
method, especially for large arrays.find
method, as it requires manual iteration.Library and purpose
The Array.from
method is used to generate the array, and it's a built-in JavaScript function that creates a new array from an iterable. Its purpose is to provide a convenient way to create arrays with a specified length and initial value.
Special JS feature/syntax
There are no special JS features or syntax mentioned in this benchmark. However, it does use ES6+ syntax, such as the const
keyword, =>
arrow functions, and template literals (\r\n
) for better readability.
Other alternatives
If you're interested in exploring alternative approaches, here are a few options:
Array.prototype.indexOf()
or Array.prototype.includes()
might be used instead of the find
method.Keep in mind that these alternatives might not be suitable for all scenarios and can have different performance characteristics.
The choice of approach ultimately depends on your specific requirements, such as the size of the array, the frequency of element access, and any additional constraints or optimizations you need to consider.