var arr = Array.from({ length: 1000 }, (_, idx) => ++idx)
arr.indexOf(500)
arr.includes(500)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
IndexOf | |
Includes |
Test name | Executions per second |
---|---|
IndexOf | 2347350.0 Ops/sec |
Includes | 1499478.8 Ops/sec |
Let's break down what's being tested in the provided benchmark.
What is being tested?
The test compares two JavaScript array methods: Array.indexOf()
and Array.includes()
. Both methods are used to find the index of a specific value within an array. However, there's a crucial difference between them:
Array.indexOf()
returns the index of the first occurrence of the specified value in the array. If the value is not found, it returns -1
.Array.includes()
also finds the index of the first occurrence of the specified value, but if the value is not found, it returns false
(or undefined
in some versions of JavaScript).Options compared
The test compares two options:
indexOf()
and includes()
use a linear search approach, which involves iterating through each element in the array until a match is found.indexOf()
returns -1
immediately when it can't find the value, while includes()
continues to iterate and returns false
only after the search is complete.Pros and cons of each approach
Other considerations:
Array.includes()
is often implemented in native code, which can make it faster than indexOf()
. However, this difference is not always significant and may depend on the specific use case.Library usage
In this benchmark, no libraries are explicitly used. Both methods are part of the built-in JavaScript API.
Special JS features
There is no special JS feature being tested in this benchmark. The focus is solely on comparing the performance of two different array methods.
Now, regarding alternative approaches:
Array.prototype.findIndex()
, which returns the index of the first element that satisfies a provided function. However, these methods are less commonly used and may not offer significant performance improvements over indexOf()
or includes()
.indexOf64()
(available in older JavaScript engines) or native arrays with optimized searching algorithms.In summary, the benchmark provides a straightforward comparison between Array.indexOf()
and Array.includes()
, highlighting their differences in performance and handling cases where the value is not found in the array.