var array = [];
for (let i = 0; i < 100000; i++) {
array.push(Math.floor((Math.random() * 10) + 1));
}
array.filter((item, index) => array.indexOf(item) != index);
array.reduce((unique, item) => unique.includes(item) ? unique : [unique, item], []);
[new Set(array)]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using indexOf | |
Using reduce | |
Using a Set |
Test name | Executions per second |
---|---|
Using indexOf | 82.2 Ops/sec |
Using reduce | 340.7 Ops/sec |
Using a Set | 744.6 Ops/sec |
Let's dive into the explanation of what's being tested in this JavaScript benchmark.
Benchmark Overview
The benchmark measures the performance of three different approaches to remove duplicates from an array:
array.indexOf()
with a callback function.reduce()
method with a callback function.[...]
) with a new Set.Library and Purpose
In this benchmark, none of the libraries are explicitly mentioned, but the use of Set
is a built-in JavaScript feature. A Set in JavaScript is an object that stores unique values, which is exactly what we need to remove duplicates from an array.
Options Compared
The three options being compared are:
array.indexOf()
with a callback function: This method checks if an element exists in the array using its value as a key. If it does, it returns the index of that element; otherwise, it returns -1.reduce()
method with a callback function: This method applies a reduction operation to an accumulator and each element in the array (from left to right) to reduce it to a single output value. In this case, we use it to check if an element is already in the accumulator (i.e., the set).[...]
) with a new Set: This method creates a new set by spreading the elements of the original array.Pros and Cons
Here are some pros and cons for each approach:
array.indexOf()
:indexOf()
has to search through the entire array to find a match.reduce()
:Set
approach). It also provides a way to reduce the output to a single value.indexOf()
.[...]
) with a Set:Other Considerations
When choosing between these approaches, consider the following factors:
indexOf()
might be sufficient. For larger arrays, using a Set
or reduce()
with a well-optimized implementation may be better.Set
approach can provide significant performance improvements.reduce()
method may require more code and understanding of the algorithm than simply using indexOf()
.Alternatives
Other alternatives for removing duplicates from an array include:
uniqBy()
, which provides a simple and efficient way to remove duplicates.However, these alternatives may not be suitable for all use cases, especially when performance is critical.