const len = 100000;
var a = Array.from({length: len}, (_, i) => i);
var b = new Set(a);
var c = Math.floor(Math.random() * len);
return a.includes(c)
return b.has(c)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array | |
Set |
Test name | Executions per second |
---|---|
Array | 13912.6 Ops/sec |
Set | 4072498.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks and explore what's being tested on this specific benchmark.
Benchmark Overview
The benchmark measures the performance difference between using Set.has()
versus Array.includes()
to check if an element exists in a set or array, respectively. The test case creates two arrays and sets with 100,000 elements, then generates a random index c
and checks if it exists in both data structures.
Options Compared
Two options are being compared:
has(c)
, it checks if the element at index c
is present in the set.Pros and Cons of Each Approach
Library and Purpose
The Array.from()
method is used to create an array with a specified length, and the Set
constructor creates a set from an array. Both are built-in JavaScript methods.
Special JS Feature/Syntax
There's no special feature or syntax being tested in this benchmark.
Other Considerations
const len = 100000;
, which ensures that the dataset size remains constant across runs.c
is generated using Math.floor(Math.random() * len)
, ensuring a uniform distribution of values.Set.has()
and Array.includes()
, providing a fair comparison.Alternatives
If you'd like to explore alternative approaches, consider these options:
Map
or WeakSet
, could potentially outperform built-in sets and arrays.Keep in mind that these alternatives might add complexity and require additional development effort. The original benchmark provides a straightforward comparison between two widely used methods, making it an excellent starting point for exploring performance optimizations in JavaScript.