var count = 4;
var arr = new Array(count);
arr.fill(null);
arr = arr.map((el, idx) => ({ id: idx }));
var randomEl = arr[Math.floor(Math.random() * count)];
var randomId = randomEl.id;
var index = arr.findIndex((el) => el.id === randomId);
var index = arr.indexOf(randomEl);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
findIndex | |
indexOf |
Test name | Executions per second |
---|---|
findIndex | 3410205.2 Ops/sec |
indexOf | 9020249.0 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
What is being tested?
The provided benchmark measures the performance difference between two JavaScript methods: Array.prototype.findIndex()
(also known as "find index") and Array.prototype.indexOf()
. Both methods are used to find the index of a specific element in an array, but they have some differences in their behavior and performance.
Options being compared
There are two main options being compared:
Array.prototype.findIndex()
: This method returns the index of the first element in the array that satisfies the provided testing function. If no elements satisfy the test, it returns -1.Array.prototype.indexOf()
: This method returns the index of the first occurrence of the specified value in the array. If the value is not found, it returns -1.Pros and Cons
Here are some pros and cons of each approach:
Array.prototype.findIndex()
:indexOf()
always returns a non-negative integer.Array.prototype.indexOf()
:findIndex()
when searching for an element that meets a specific condition, since it has to iterate over the entire array.Library
There is no library being used in this benchmark. Both Array.prototype.findIndex()
and Array.prototype.indexOf()
are native JavaScript methods.
Special JS feature or syntax
The benchmark uses the map()
method, which creates a new array with the results of applying a provided function to each element in an existing array. The map()
method is a built-in JavaScript method that is supported by most modern browsers and Node.js environments.
Other alternatives
If you wanted to implement your own indexing algorithm, you could use a simple loop or recursion to find the index of an element in an array. However, these approaches would likely be slower and less efficient than using native methods like findIndex()
and indexOf()
.