var array=[];
for(let i=0; i<2000;i++){
array[i] = i;
}
var set = new Set(array);
set.has(1855);
array.indexOf(1855);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
set | |
array |
Test name | Executions per second |
---|---|
set | 38738992.0 Ops/sec |
array | 553235.4 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares two approaches for checking if an element exists in a data structure: using a Set
or an array with indexOf()
. The goal is to measure which approach is faster.
Options Compared
Two options are compared:
Set
is created from the generated array and then used to check if a specific element (1855) exists in it using the has()
method.indexOf()
method is called on this array to find the index of 1855.Pros and Cons
Library and Purpose
In this benchmark, the Set
object from the JavaScript API is used. A Set
is a collection of unique values that can be added, removed, or checked for existence.
Special JS Feature/Syntax
There's no special JavaScript feature or syntax being tested in this benchmark. It's a straightforward comparison of two simple approaches.
Other Alternatives
If you were to rewrite this benchmark, you might consider adding more options, such as:
in
operatorHowever, these alternatives may not be immediately relevant or representative of common use cases.
Benchmark Preparation Code Explanation
The preparation code creates an array of 2000 elements and a Set
from it. This ensures that both options are testing the same dataset and can compare their performance accurately.
Similarly, the test case definitions specify the benchmark definition for each option (using set.has()
or array.indexOf()
) and provide a name for the test case.
Latest Benchmark Result
The latest benchmark results show the execution counts per second for each option in Firefox 82 on a desktop device. The results indicate that using a Set
is faster than using an array with indexOf()
.