var arr = new Array(300);
arr.fill({
id: 0
});
arr = arr.map((el, idx) => el.id = idx);
var foo = Math.floor(Math.random() * 15000);
arr.findIndex((itm) => itm.id === foo);
for (let i = 0; i < arr.length; i++) {
if (arr[i].id === foo) break;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
findIndex | |
for loop |
Test name | Executions per second |
---|---|
findIndex | 76952.4 Ops/sec |
for loop | 26105.1 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
What is tested?
The provided benchmark tests two approaches for finding an element in an array: findIndex
and a traditional for
loop.
Options compared
findIndex
: This method returns the index of the first element in the array that satisfies the provided condition. In this case, we're using it to find an element with id
equal to a randomly generated number (foo
).for loop
: This is a traditional iteration approach where we use a counter variable (i
) to iterate through each element in the array and check if its id
matches the target value. If found, we break out of the loop.Pros and cons of each approach
findIndex
:for loop
:findIndex
, especially for large arrays, due to the overhead of iteration and checking each element individually.Other considerations
findIndex
is usually faster.findIndex
can be concise, some developers might find it harder to understand due to the lack of explicit iteration logic. On the other hand, for loop
can be more readable, but may require more code.Library usage
In this benchmark, no specific library is used beyond the built-in JavaScript array methods and functions (e.g., Math.floor
, Math.random
). However, MeasureThat.net might use some internal libraries or utilities to manage the benchmarking process.
Special JS feature/syntax
This benchmark does not use any special JavaScript features or syntax. It's a straightforward comparison of two basic approaches for finding an element in an array.
Alternatives
If you wanted to compare other approaches, you could consider adding additional test cases, such as:
forEach
and checking if the callback is executedevery
and checking if all elements match the condition