var array = Array.from({length: 40}, () => Math.floor(Math.random() * 140));
const f = new Set(array)
const b = array.filter((i,index) => array.indexOf(i)=== index)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Set spread | |
Filter |
Test name | Executions per second |
---|---|
Set spread | 2604980.5 Ops/sec |
Filter | 2210875.5 Ops/sec |
The benchmark JSON provided evaluates two different approaches for obtaining unique values from an array in JavaScript: using a Set
and using the filter
method combined with indexOf
. Here’s a breakdown of the different options compared, their pros and cons, and other considerations.
Set Method
const f = new Set(array);
Pros:
Set
is quite efficient. In this test, the execution rate is about 1,763,329.25 operations per second, which is reasonably fast.Set
inherently stores only unique items.Set
can be more readable for those familiar with its properties.Cons:
Set
may consume more memory than a simple array, especially if dealing with a large number of values.Filter Method
const b = array.filter((i,index) => array.indexOf(i) === index);
Pros:
filter
method is a common functional programming approach in JavaScript, which may appeal to developers with a background in functional programming.Cons:
Set
, achieving about 1,919,872.5 operations per second.indexOf
within the filter
results in potentially O(N^2) complexity when filtering the array, as it must traverse the array for each item being checked.Set
and Array.prototype.filter
), which are built into the language. This means there's no external library overhead, keeping it lightweight.Besides the two approaches tested, there are other alternatives for obtaining unique values from an array in JavaScript:
Using reduce
Method:
const unique = array.reduce((acc, current) => {
if (!acc.includes(current)) {
acc.push(current);
}
return acc;
}, []);
This would have a similar performance issue as the filter
method, making it potentially inefficient for large arrays.
Using forEach
:
Another approach could be to use forEach
to manually accumulate unique values over time in a new array, maintaining unique values with checks. This also tends to be less efficient.
Sort and Deduplicate: Sort the array first, then run a loop to remove duplicates. This may add complexity in terms of handling the sorting operation.
In conclusion, the benchmark clearly indicates that using a Set
is likely to be the better performing option for obtaining unique values from an array in JavaScript. It balances performance, readability, and simplicity, making it a preferred choice in modern JavaScript development. However, the filter
method might still be used for its compatibility with older codebases where ES6 features are not available.