var arr = new Array(15000);
arr.fill({ id: 0 });
arr = arr.map((el, idx) => idx);
var foo = Math.floor(Math.random() * 15000);
var index = arr.indexOf(foo);
var index = arr.findIndex(el => el === foo);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.indexOf | |
Array.prototype.findIndex |
Test name | Executions per second |
---|---|
Array.prototype.indexOf | 19146.1 Ops/sec |
Array.prototype.findIndex | 326.4 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Overview
The provided JSON represents a benchmark test comparing two methods for finding an element in an array: indexOf
and findIndex
. The test is designed to measure which method performs better in terms of speed.
Options Compared
There are two options being compared:
Array.prototype.indexOf
: This method returns the index of the first occurrence of a specified value within the array, or -1 if the value is not found.Array.prototype.findIndex
: This method returns the index of the first element in an array that satisfies the provided testing function.Pros and Cons
indexOf
:findIndex
:indexOf
, allows for a custom callback function to test each element in the array. It has a time complexity of O(n) as well, but it's generally faster than indexOf
because it stops searching once it finds the first match.Library and Special JS Features
There are no specific libraries being used in this benchmark, but there is a use of Math.random()
to generate a random index for the array elements.
No special JS features are being tested in this benchmark.
Other Considerations
When writing benchmarks like this one, it's essential to consider factors such as:
Alternatives
Other alternatives to measure performance differences between indexOf
and findIndex
include:
Array.prototype.includes()
instead of indexOf
, as it's more concise and readable.By understanding the basics of these methods and their performance characteristics, you'll be better equipped to make informed decisions about when to use indexOf
versus findIndex
in your JavaScript applications.