const item_1 = Math.floor(Math.random() * 1);
const array_1 = new Array(1).map((_, i) => i);
const set_1 = new Set(array_1);
const item_2 = Math.floor(Math.random() * 2);
const array_2 = new Array(2).map((_, i) => i);
const set_2 = new Set(array_2);
const item_4 = Math.floor(Math.random() * 4);
const array_4 = new Array(4).map((_, i) => i);
const set_4 = new Set(array_4);
const item_8 = Math.floor(Math.random() * 8);
const array_8 = new Array(8).map((_, i) => i);
const set_8 = new Set(array_8);
array_1.includes(item_1)
set_1.has(item_1)
array_2.includes(item_2)
set_2.has(item_2)
array_4.includes(item_4)
set_4.has(item_4)
array_8.includes(item_8)
set_8.has(item_8)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array_1 | |
set_1 | |
array_2 | |
set_2 | |
array_4 | |
set_4 | |
array_8 | |
set_8 |
Test name | Executions per second |
---|---|
array_1 | 49544920.0 Ops/sec |
set_1 | 58616264.0 Ops/sec |
array_2 | 44347332.0 Ops/sec |
set_2 | 58414468.0 Ops/sec |
array_4 | 44401620.0 Ops/sec |
set_4 | 59612848.0 Ops/sec |
array_8 | 38383360.0 Ops/sec |
set_8 | 59723020.0 Ops/sec |
The benchmark defined in the provided JSON compares the performance of two different methods for checking the existence of items in collections: using an Array.includes()
method versus a Set.has()
method. The benchmark focuses on a small number of items to assess the performance differences between these two approaches. Here's a detailed breakdown:
Array.includes(item):
Set.has(item):
Pros:
Cons:
Pros:
Cons:
Set.has()
outperformed Array.includes()
, particularly notable when more items were involved.In addition to using Arrays and Sets, there are alternative methods to consider for similar operations:
The benchmark allows engineers to understand the trade-offs between two fundamental data structures in JavaScript. As JavaScript applications scale and performance becomes a critical factor, choosing the right data structure based on the expected operations can substantially improve efficiency. Sets generally offer a more performant solution for membership tests, while arrays remain valuable for ordered collections and small datasets.