var values = []
for (var i = 0; i < 1000000; i++) {
values.push[i]
}
var TEST_NUM = 897495
var result = values.find(v => v === TEST_NUM)
var TEST_NUM = 897495
var result = values.includes(TEST_NUM)
var TEST_NUM = 897495
var result = values.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 | 9861495.0 Ops/sec |
Array.includes | 13215050.0 Ops/sec |
Array.indexOf | 12808813.0 Ops/sec |
Let's break down the provided benchmark.
Benchmark Definition
The benchmark measures the performance of three different methods for finding an element in an array: Array.includes
, Array.indexOf
, and Array.find
. These methods are all used to search for a specific value within the large array created by the script preparation code.
Script Preparation Code
The script generates a large array of 1 million elements, each with a unique index. This is done using a simple JavaScript loop:
for (var i = 0; i < 1000000; i++) {
values.push[i] = i;
}
This creates an array where each element has the same value as its index.
Html Preparation Code
There is no HTML preparation code provided, so we can assume that this benchmark only tests JavaScript performance and does not involve any web page rendering or other external factors.
Individual Test Cases
The three test cases are:
Array.find
: This method uses a callback function to find the first element in the array that satisfies a condition.var TEST_NUM = 897495;
var result = values.find(v => v === TEST_NUM);
Array.includes
: This method checks if an element with the specified value exists in the array.var TEST_NUM = 897495;
var result = values.includes(TEST_NUM);
Array.indexOf
: This method returns the index of the first occurrence of the specified value, or -1 if it is not found.var TEST_NUM = 897495;
var result = values.indexOf(TEST_NUM) !== -1;
Pros and Cons
Here's a brief summary of each method:
Array.includes
:Array.indexOf
:Array.find
:includes
or indexOf
due to its extra overhead. Average time complexity is O(n).Library and Syntax
There are no libraries used in this benchmark.
Special JS Features
None mentioned.
Other Alternatives
Some alternative methods for finding an element in an array include:
for
loop with indexing: var result = 0; while (result < values.length && values[result] !== TEST_NUM) { result++; }
includes()
method with a callback function: values.includes(v => v === TEST_NUM)
some()
and findIndex()
methods: values.some((v, i) => v === TEST_NUM);
or values.findIndex((v, i) => v === TEST_NUM)
However, these alternatives are not part of the standard JavaScript array API and may have different performance characteristics.