var arr = [];
for(let i = 0; i < 15000; i++) {arr[i] = i;}
var foo = Math.floor(Math.random() * 15000);
const index = arr.findIndex((element) => element === foo);
const index = arr.indexOf(foo);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
findIndex | |
indexOf |
Test name | Executions per second |
---|---|
findIndex | 1758.6 Ops/sec |
indexOf | 218150.4 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
What is being tested?
The provided JSON represents a JavaScript microbenchmark that compares the performance of two methods to find an element in an array: Array.prototype.findIndex()
and Array.prototype.indexOf()
. The test case uses a simple array of 15,000 elements, each with a unique value between 0 and 14,999. A random index is generated, and the benchmark measures how many times each method can execute within a second.
Options being compared:
The two options being compared are:
Array.prototype.findIndex()
: This method returns the index of the first element that satisfies the provided condition (in this case, finding an element equal to the randomly generated value). If no such element is found, it returns -1.Array.prototype.indexOf()
: This method returns the index of the first occurrence of a specified value in the array. If the value is not found, it returns -1.Pros and Cons:
Array.prototype.findIndex()
Pros:
indexOf
Cons:
Array.prototype.indexOf()
Pros:
findIndex
for small arrays or exact matchesCons:
findIndex
findIndex
returns -1 when no elements satisfy the conditionLibrary:
None of the methods in question use any external libraries.
Special JS feature/syntax:
The benchmark uses JavaScript's built-in functions and syntax. No special features or syntax are used.
Other considerations:
To provide a more accurate comparison, it would be helpful to consider other factors such as:
Alternatives:
Other alternatives for finding an element in an array could include:
Array.prototype.includes()
: This method returns a boolean indicating whether the specified value is present in the array.Array.prototype.some()
and Array.prototype.filter()
: These methods can be used to find all indices that satisfy a condition, but may have different performance characteristics.Keep in mind that these alternatives may not be as concise or expressive as findIndex
and indexOf
, respectively.