var a = [];
for(let i = 0; i < 100000; i++){a.push(i)}
var b = new Set(a)
return a.includes(Math.floor(Math.random()*100000))
return b.has(Math.floor(Math.random()*100000))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
includes | |
lookup |
Test name | Executions per second |
---|---|
includes | 114962.9 Ops/sec |
lookup | 2239797.5 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and the pros/cons of each approach.
Benchmark Definition:
The benchmark measures the performance difference between two approaches:
set.has
: Checking if an element exists in a Set
data structure using the has()
method.array.includes
: Searching for an element in an array using the includes()
method.Script Preparation Code:
var a = [];
for (let i = 0; i < 100000; i++) {
a.push(i);
}
var b = new Set(a);
This code creates an array a
with 100,000 elements and then converts it to a Set
data structure called b
.
Html Preparation Code: There is no HTML preparation code provided.
Individual Test Cases:
The benchmark consists of two test cases:
includes
: Measures the performance of searching for an element in the array using includes()
.lookup
: Measures the performance of checking if an element exists in the set using has()
.Library and Purpose: In both test cases, a library is used:
Set
data structure is used to create a set from the array.includes()
, has()
, and the Set
data structure itself are leveraged.Special JS Feature/Syntax: There's one special feature in use here:
includes()
method is used to search for an element in the array. This method was introduced in ECMAScript 2015 (ES6) as a way to check if an element exists within a sequence (like an array or string).Pros and Cons:
set.has
:
Pros:
Cons:
Set
data structure to be created initially, which can be memory-intensive.array.includes
:
Pros:
Cons:
set.has
.Comparison:
The benchmark measures the performance difference between these two approaches for large datasets. In general, set.has
is expected to be faster due to its average time complexity of O(1), while array.includes
has a higher time complexity (O(n)).
Other Alternatives:
If you were to test alternative methods, some options could include:
includes()
versus indexOf()
(which returns the index of the first occurrence, not just a boolean result).Keep in mind that the choice of alternative methods would depend on specific requirements and use cases. The current benchmark focuses on comparing the performance of two widely used JavaScript methods for large datasets.