var arr = new Array(15000);
for (var i = 0; i < 15000; i++) {
arr.fill({ id: i });
}
numArr = arr.map((el, idx) => el.id = idx);
var foo = Math.floor(Math.random() * 15000);
var index = arr.findIndex((obj) => obj.num === foo);
var index = numArr.indexOf(foo);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
findIndex | |
indexOf |
Test name | Executions per second |
---|---|
findIndex | 747.1 Ops/sec |
indexOf | 635815.9 Ops/sec |
Let's break down the provided JSON and explain what's being tested, compared, and other considerations.
What is being tested?
The benchmark measures the performance of two JavaScript methods: indexOf
and findIndex
. These methods are used to find the index of a specific element within an array. The test creates a large array of 15,000 elements with a unique identifier (id
) for each element, and then uses these arrays in both tests.
Options compared
The two options being compared are:
indexOf
findIndex
Both methods take two arguments: the array to search in and the value to search for. However, they differ in their approach:
indexOf
returns the index of the first occurrence of the specified value within the array.findIndex
returns the index of the first occurrence of the specified value within the array, but it returns -1 if no element is found.Pros and Cons
Here are some pros and cons for each approach:
indexOf
:findIndex
, especially for small arrays.findIndex
:indexOf
, especially for small arrays.Library and purpose
In this test case, the map()
function is used to create a new array with the same elements as the original array, but with the indices assigned instead of the values. This creates two different arrays:
arr
: The original array with unique identifiers (id
) for each element.numArr
: A new array created by mapping the original array and assigning the indices to the values.Special JavaScript feature or syntax
The map()
function is a built-in JavaScript method that creates a new array with the results of applying a provided function on every element in this array. It's used here to create two different arrays, which are then used in both tests.
Other alternatives
There are other methods you could use to achieve similar results:
Array.prototype.indexOf()
: This is an older method for finding the index of a value within an array.Array.prototype.findIndex()
: This is another method for finding the index of a value within an array, but it's generally slower than indexOf
.However, in this test case, the focus is on comparing the performance of indexOf
and findIndex
, so using a different approach would likely change the results.