<script src='https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js'></script>
var array = [];
for (let i = 0; i < 100000; i++) {array.push(~~(Math.random() * 2000))}
return [new Set(array)]
return _.uniq(array);
return Array.from( new Set(array) );
const visited = {};
const uniques = [];
const initial = array;
for(let i=0;i<initial.lenght;i++){
if(!visited[initial[i]]) {
visited[initial[i]] = true;
uniques.push(initial[i]);
}
}
return uniques
const visited = {};
const uniques = [];
const initial = array;
for(let i=0;i<initial.lenght;i++){
if(!(initial[i] in visited)) {
visited[initial[i]] = undefined;
uniques.push(initial[i]);
}
}
return uniques
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Spread | |
use lodash | |
Array.from | |
For | |
For memory optimized |
Test name | Executions per second |
---|---|
Spread | 535.4 Ops/sec |
use lodash | 538.8 Ops/sec |
Array.from | 559.1 Ops/sec |
For | 15491293.0 Ops/sec |
For memory optimized | 15547500.0 Ops/sec |
Benchmark Overview
The provided benchmark compares the performance of four different approaches to find unique elements in an array:
Array.from(new Set(array))
_.uniq(array)
(using Lodash library)for
loop with manual handling of unique elementsfor
loop with optimized memory usageOptions Comparison
The benchmark tests each approach on a fixed dataset of 100,000 random integers between 0 and 2000.
Set
data structure to remove duplicates from the array.(using Lodash library)**: Uses the
uniq` function from Lodash to remove duplicates from the array.visited
object.in
operator instead of indexing to check for unique elements.Library Overview
The Lodash library is a popular utility library that provides various functions for common tasks, including data manipulation. In this benchmark, _.uniq(array)
is used to remove duplicates from an array.
Special JS Features or Syntax
None mentioned in the provided information.
Benchmark Results
The latest benchmark results show that:
Other Alternatives
Some alternative approaches that could be tested in a benchmark include:
Map
data structure instead of Set