<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.5/lodash.min.js"></script>
var firstEqual = [];
var secondEqual = [];
for (var i=0; i<=1000000; i++) {
firstEqual.push(i);
secondEqual.push(i);
}
var arrayToDedup = [firstEqual, secondEqual];
_.uniq(arrayToDedup);
[new Set(arrayToDedup)]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash Uniq | |
Javascript Set |
Test name | Executions per second |
---|---|
Lodash Uniq | 3.1 Ops/sec |
Javascript Set | 2.7 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares two approaches to remove duplicates from an array:
Set
object to remove duplicates from an array.Script Preparation Code
The script preparation code creates two identical arrays, firstEqual
and secondEqual
, with 1 million elements each. The arrayToDedup
variable is then created by concatenating the two arrays using the spread operator ([...firstEqual, ...secondEqual]
). This array will be used as input for both benchmark tests.
Html Preparation Code
The HTML preparation code includes a script tag that loads the Lodash library version 4.17.5 from a CDN.
Test Cases
There are two test cases:
_.uniq
function from Lodash to remove duplicates from arrayToDedup
.Set
object to remove duplicates from arrayToDedup
.Pros and Cons of Each Approach
Other Considerations
When choosing between these approaches, consider the trade-offs between:
Native JavaScript Features
The benchmark uses a feature that is widely supported in modern browsers: the Set
object. The Set
object is implemented in native JavaScript and provides an efficient way to remove duplicates from arrays.
In summary, this benchmark allows users to compare the performance of two approaches to remove duplicates from arrays: using Lodash Uniq or native JavaScript Set. By understanding the pros and cons of each approach, developers can choose the best solution for their specific use case.
Alternative Approaches
Other alternatives for removing duplicates from arrays include:
Array.prototype.filter()
and checking for duplicate values._.uniq
.