const arr1 = Array.from({ length: 1_000_000 }, () =>
Math.floor(Math.random() * 100_000),
)
const arr2 = Array.from({ length: 1_000_000 }, () =>
Math.floor(Math.random() * 100_000),
)
const fn = () => {
for (const el of arr1) {
if (arr2.includes(el)) return true
}
}
fn()
const arr1 = Array.from({ length: 1_000_000 }, () =>
Math.floor(Math.random() * 100_000),
)
const arr2 = Array.from({ length: 1_000_000 }, () =>
Math.floor(Math.random() * 100_000),
)
const fn = () => {
const set = new Set(arr1)
for (const el of arr2) {
if (set.has(el)) return true
}
}
fn()
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Includes | |
new Set |
Test name | Executions per second |
---|---|
Includes | 4.8 Ops/sec |
new Set | 4.4 Ops/sec |
Benchmark Overview
The provided benchmark, hosted on MeasureThat.net, compares the performance of two approaches to check if an element exists in an array: using includes()
and creating a new Set
from the array.
What is being tested?
In this benchmark, we have two test cases:
includes()
method to search for elements in the first array (arr1
) within the second array (arr2
). The implementation involves iterating over each element in arr1
and checking if it exists in arr2
.arr1
, and then an element is checked to see if it exists in the set.Options compared
The two options being compared are:
includes()
methodSet
from the arrayThese two approaches have different performance characteristics, which are the focus of this benchmark.
Pros and Cons
Pros:
Cons:
Pros:
includes()
for large arrays because it uses a more optimized data structure (a hash table) for lookups.Cons:
Library/Technique
The includes()
method is a built-in JavaScript function that uses a linear search algorithm. The creation of a new Set
involves converting the array into an object using the Array.from()
and Set()
constructors, which creates a hash table for efficient lookups.
Special JS Feature/Syntax
There are no special features or syntaxes used in this benchmark beyond standard JavaScript.
Other Considerations
When choosing between these two approaches, consider the specific requirements of your application:
includes()
might be sufficient.Alternatives
If you're looking for alternative approaches, consider the following:
contains
function, which is optimized for performance and uses a similar approach to creating a set.Keep in mind that these alternatives may require more expertise and resources than the built-in includes()
method.