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 | 82.1 Ops/sec |
Array.includes | 577.3 Ops/sec |
Array.indexOf | 572.9 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Overview
The provided benchmark measures the performance of three methods to search for an element in an array:
Array.includes
Array.find
Array.indexOf
The test case uses a large array (values
) with 1,000,000 elements, and searches for a specific value (TEST_NUM
).
Library and Special Features
None of the test cases use any external libraries or special JavaScript features that are not part of the standard language.
Options Compared
The three methods compared are:
Array.includes
Array.find
Array.includes
and Array.indexOf
, especially for large arrays. It's designed specifically for finding a single value in an array and returns it immediately if found.Array.indexOf
Array.includes
, but can be more efficient in some cases. It returns the index of the first occurrence of the specified value, which can be useful for certain use cases.Array.find
for large arrays with many occurrences of the desired element.Benchmark Results
The latest benchmark results show that:
Array.includes
is the fastest method, executing approximately 577 executions per second on a Chrome 91 browser and Mac OS X 10.14.6 operating system.Array.indexOf
is slightly slower than Array.includes
, executing around 82 executions per second.Array.find
is the slowest method, executing only about 57 executions per second.Other Alternatives
If you need to search for an element in an array, other alternatives could include:
forEach
: This method iterates over the array and executes a callback function for each element. While not specifically designed for finding an element, it can be used with some modifications.Map
data structure: If you need to search for a value in an associative array (object), using a Map
data structure can be more efficient.Keep in mind that the best approach depends on your specific use case and requirements.