var arr = new Array(15000);
arr.fill('')
arr = arr.map(el => Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 8));
var foo = 'erjhfdjh';
arr[7500]=foo;
var obj = arr.reduce((acc,key,i)=>{acc[key]=i;return acc},{});
var index = arr.indexOf(foo);
var index = arr.findIndex(o => o===foo);
var index = obj[foo]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
indexOf | |
findIndex | |
object property |
Test name | Executions per second |
---|---|
indexOf | 9665.4 Ops/sec |
findIndex | 242.3 Ops/sec |
object property | 937580.4 Ops/sec |
I'd be happy to explain what's being tested in this JavaScript microbenchmark.
Overview
The benchmark is designed to compare the performance of three different approaches to find an element in an array: indexOf
, findIndex
, and accessing an object property directly.
Script Preparation Code
The script preparation code creates a large array arr
with 15,000 elements, fills it with random strings, and sets one element to the string 'erjhfdjh'
. It also creates an object obj
by reducing the array to a map of indices to original indices.
Test Cases
There are three test cases:
indexOf()
method to find the index of the target string 'erjhfdjh'
in the array.findIndex()
method to find the index of the first element that matches the target string.obj[foo]
, where foo
is the same as before.Options Compared
The benchmark compares the performance of these three approaches:
indexOf
: Simple and widely supported, but may have performance issues for large arrays.findIndex
: More precise than indexOf
, but slower due to its more complex algorithm.indexOf
can be slow for very large arrays or when the element is not found.findIndex
may not work as expected if the array contains duplicate elements.Pros and Cons
Here's a brief summary of each approach:
indexOf
, but slower. Cons: slower, may not work with duplicate elements.Library Used
The benchmark uses the built-in JavaScript array and object methods, which are part of the ECMAScript standard.
Special JS Feature or Syntax
There is no special feature or syntax used in this benchmark. It only relies on standard JavaScript features and methods.
Other Alternatives
If you need to find an element in a large array, other alternatives might include:
Array.prototype.some()
or Array.prototype.every()
, which can be faster than indexOf
for very large arrays.Keep in mind that these alternatives may have trade-offs in terms of complexity, performance, and code readability.