var a = [];
for(i=0;i<10000;i++) a.push(i);
var b = new Set(a)
a.indexOf(342);
b.has(342);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array | |
set |
Test name | Executions per second |
---|---|
array | 591599424.0 Ops/sec |
set | 576916992.0 Ops/sec |
In the benchmark defined by MeasureThat.net titled "set vs array find if exists 2," two different data structures in JavaScript—an array and a Set
object—are compared to determine their performance when checking for the existence of a specific value (in this case, the number 342). Below is a detailed breakdown of the benchmarking process, the tested options, their pros and cons, and general considerations.
Array (indexOf
):
a.indexOf(342);
Set (has
):
b.has(342);
In this benchmark, no external JavaScript libraries are used; instead, it relies solely on built-in JavaScript features, specifically the Array
and Set
data structures.
Array:
indexOf
method is used, which searches for a specified element and returns its first index in the array. If the value is not found, it returns -1. This method has a time complexity of O(n) because it must iterate through the array to find the specified value.Set:
has
method of the Set
object checks for the existence of a value. The Set
structure maintains unique values, offering faster lookups. The time complexity for this operation is generally O(1), given that Set
is optimized for fast existence checks.indexOf
)Pros:
Cons:
has
)Pros:
Cons:
Choosing between arrays and sets in the context of checking for the existence of a value largely depends on the specific requirements of the application. If the data being processed is relatively small and performance is not the primary criterion, arrays and their associated methods (like indexOf
) can suffice.
On the other hand, if performance and scalability are priorities—especially when dealing with frequent lookups or large datasets—using a Set
is a better approach.
While this benchmark focuses on Array
and Set
, there are other alternatives to consider:
Map
provides fast lookups similar to Set
but for structured data.Set
.In conclusion, the benchmark illustrates a clear performance difference between using an array and a set to verify the existence of an element, favoring the Set
approach for larger datasets or frequent searches due to its optimized time complexity.