var arr = [];
var i = 0;
while (i < 15001) arr[i] = i++;
const index = arr.indexOf(15000);
const included = arr.includes(15000);
const item = arr.find(item => item === 15000);
const index = arr.findIndex(item => item === 15000);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
indexOf | |
includes | |
find | |
findIndex |
Test name | Executions per second |
---|---|
indexOf | 790909.1 Ops/sec |
includes | 788998.3 Ops/sec |
find | 115581.2 Ops/sec |
findIndex | 118133.5 Ops/sec |
Let's break down the provided JSON and explain what is tested, compared options, pros/cons, and other considerations.
Benchmark Definition
The benchmark measures the performance of four different ways to find an element in a large array:
arr.indexOf(15000)
arr.includes(15000)
arr.find(item => item === 15000)
arr.findIndex(item => item === 15000)
Script Preparation Code
The script preparation code creates a large array of length 15,001 and populates it with integers from 0 to 14,999.
var arr = [];
var i = 0;
while (i < 15001) arr[i] = i++;
This code is run before each test case to ensure a consistent baseline.
Options Compared
The four options compared are:
indexOf
: Returns the index of the first occurrence of 15000
in the array.includes
: Returns a boolean indicating whether 15000
is included in the array.find
: Returns the value of the first element in the array that satisfies the provided callback function (in this case, item => item === 15000
).findIndex
: Similar to find
, but returns the index of the first occurrence instead of the value.Pros/Cons and Considerations
Here's a brief summary of each option:
indexOf
:includes
:indexOf
for large arrays (using binary search).find
:indexOf
, can be used with custom callback functions.findIndex
:includes
.In general, for large arrays, includes
and findIndex
are likely to be the fastest options, followed by indexOf
. However, if you need to perform additional operations on the found element (e.g., using find
), it may outweigh the performance cost.
Library Usage
None of the provided code uses external libraries. The array manipulation is a built-in JavaScript feature.
Special JS Features or Syntax
The benchmark uses some advanced features:
find
and findIndex
.Other Alternatives
If you want to test other approaches, consider the following alternatives:
Array.prototype.indexOf()
with for...of
loop: Instead of using while
, use a for...of
loop to create and populate the array.Math.random()
for element distribution: Instead of using integers from 0 to 14,999, generate random numbers within the same range.Keep in mind that these alternatives may affect the benchmark's accuracy and applicability.