var object = {
items: Array.from({
length: 100
}, (_, i) => ({
id: i,
name: `Item-${i}`,
}))
};
// Randomly select ~75% of items
var selectedItems = object.items
.filter(() => Math.random() > 0.25)
.map(item => item.id);
var set = new Set(selectedItems);
return object.items.every(({ id }) => selectedItems.includes(id));
return object.items.every(({ id }) => set.has(id))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.every => Array.includes | |
Array.every => Set.has |
Test name | Executions per second |
---|---|
Array.every => Array.includes | 46419228.0 Ops/sec |
Array.every => Set.has | 34525136.0 Ops/sec |
The provided benchmark tests the performance of two different approaches for checking if a set of selected item IDs exists within a collection of objects. Specifically, it compares:
Array.prototype.includes
within Array.prototype.every
Set
's has
method within Array.prototype.every
1. Array.every => Array.includes
:
every
method on an array of objects, checking each object's id
against the selectedItems
array using includes
. includes
method performs a linear search for every id
, resulting in a time complexity of O(n * m) where n is the number of items in object.items
and m is the number of selectedItems
. This can become expensive for large datasets.2. Array.every => Set.has
:
Set
to store the selectedItems
, and checks for the existence of each id
using the has
method while iterating through object.items
with every
.has
method on a Set
allows for average-time complexity of O(1) for lookups, resulting in a total time complexity of O(n) for the entire operation.includes
when dealing with larger arrays.Set
, which may be a consideration in memory-limited environments.includes
.Set
object, which is designed for storing unique values of any type and provides efficient methods for checking existence (has
), adding (add
), and deleting (delete
). Using a Set
is considered an optimal choice when performing frequent membership checks.The benchmark results indicate a performance difference between the two approaches:
The choice between these two methods should be dictated by context:
includes
may be preferable, despite potential inefficiencies.Set
is usually the better option due to its O(1) lookup time.Alternatives:
for
or forEach
) with direct comparisons could be an option, though the performance outcome may not surpass that of using Set
.In summary, the benchmark provides insight into performance trade-offs between readability and efficiency, emphasizing the importance of choosing the right tools based on data size and application needs.