var unique = (value, index, self) => {
return self.indexOf(value) === index;
};
var items = [];
for (i = 0; i < 1000000; i++) {
items.push(Math.floor(Math.random() * 100));
}
_.uniq(items)
items.filter(unique);
[new Set(items)];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
ld uniq | |
index of | |
set |
Test name | Executions per second |
---|---|
ld uniq | 61.6 Ops/sec |
index of | 33.6 Ops/sec |
set | 58.4 Ops/sec |
Let's break down the provided JSON and benchmark results.
Benchmark Definition
The Script Preparation Code
section defines two small JavaScript functions:
unique
: This is an arrow function that takes three arguments: value
, index
, and self
. It returns true
if the value
is found at its current index
in the array (self.indexOf(value) === index
). This function is not directly used in the benchmark but serves as a starting point for creating a custom filter.items
is an array of 1,000,000 random integers.The Html Preparation Code
section is empty, which means there's no additional setup required for the benchmark.
Individual Test Cases
There are three test cases:
_.uniq(items)
: This test case uses Lodash's uniq
function to remove duplicates from the items
array.items.filter(unique)
: This test case filters the items
array using a custom filter function (unique
) that we defined earlier.[...new Set(items)]
: This test case converts the items
array to an array of unique values using the spread operator and a new Set
.Comparison of Approaches
uniq
:unique
):uniq
, requires more code and testing effort.Set
:uniq
for very large datasets.Special JS Features
None are explicitly mentioned in the benchmark definition or test cases. However, using Lodash requires understanding its API and how to import it (e.g., import _ from 'lodash';
) since it's not a built-in JavaScript function.
Other Alternatives
If you don't want to use Lodash, you could:
Set
or Map
).Keep in mind that each approach has its trade-offs and might not be suitable for all scenarios.
In this benchmark, Lodash's uniq
appears to be the fastest method, but it's essential to understand the pros and cons of each approach before choosing one.