var values = []
for (var i = 0; i < 1000000; i++) {
values.push({i})
}
var TEST_NUM = 897495
var result = values.find(({i}) => i === TEST_NUM)
var TEST_NUM = 897495
var mappedValues = values.map(({i}) => i)
var result = mappedValues.includes(TEST_NUM)
var TEST_NUM = 897495
var mappedValues = values.map(({i}) => i)
var result = mappedValues.indexOf(TEST_NUM) !== -1
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.find | |
Array.includes | |
Array.indexOf |
Test name | Executions per second |
---|---|
Array.find | 92.3 Ops/sec |
Array.includes | 65.1 Ops/sec |
Array.indexOf | 61.9 Ops/sec |
Overview
The provided JSON represents a JavaScript benchmark test on MeasureThat.net. The test compares the performance of three different approaches to find an element in an array: Array.find()
, Array.includes()
, and Array.indexOf()
.
Benchmark Definition
The benchmark definition specifies the following:
i
.Array.find()
: Find the first element in the array that matches the condition i === TEST_NUM
, where TEST_NUM
is a constant value (897495).Array.includes()
: Check if the array contains the element with the index TEST_NUM
.Array.indexOf()
: Get the index of the element with the index TEST_NUM
in the array.Options Compared
The benchmark compares three different approaches to find an element in the array:
Array.find()
: This method returns the first element that satisfies the provided testing function. It is a more concise and expressive way to find an element in the array.Array.includes()
: This method checks if the array contains an element with the specified value (or index, in this case). It returns true
if the array contains the element, and false
otherwise.Array.indexOf()
: This method returns the index of the first occurrence of the specified value. If the value is not found, it returns -1
. In this benchmark, we use a negation (!== -1
) to check for presence.Pros and Cons
Here are some pros and cons of each approach:
Array.find()
: Pros:undefined
if no matching element is foundArray.includes()
: Pros:true
or false
)
Cons:Array.find()
Array.indexOf()
: Pros:-1
if the element is not found, which can lead to confusionLibrary: None
There are no libraries involved in this benchmark.
Special JS Feature or Syntax: None
There are no special JavaScript features or syntax used in this benchmark.
Alternative Approaches
Other approaches to find an element in an array could include:
Array.prototype.some()
and a callback functionArray.prototype.reduce()
with an initial value of 0
However, these approaches are not included in this benchmark.
Note that the performance differences between these methods can be significant, especially for large arrays. Therefore, it's essential to choose the right approach depending on your specific use case and performance requirements.