<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
var values = _.fill(Array(100000), null).map(() => _.random(0,9));
const results = _.uniq(values);
const results = [new Set(values)];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash uniq | |
Set |
Test name | Executions per second |
---|---|
lodash uniq | 288.6 Ops/sec |
Set | 290.9 Ops/sec |
Let's break down the benchmark and explain what's being tested, compared, and considered.
What is tested: The benchmark compares two approaches to remove duplicates from an array:
_.uniq()
: This function removes duplicate values from an array while preserving the original order.Set
object: A built-in JavaScript data structure that automatically eliminates duplicate values when used as a collection of unique elements.Options compared: The benchmark compares the performance of two approaches:
_.uniq()
Set
objectPros and Cons of each approach:
_.uniq()
: Pros:Set
object: Pros:Set
data structure and its behavior.Library and purpose:
The _.uniq()
function from Lodash is a utility function that removes duplicate values from an array while preserving the original order. It returns a new array with unique elements, leaving the original array unchanged.
Special JS feature or syntax: There is no special JavaScript feature or syntax used in this benchmark.
Other alternatives: For removing duplicates from an array, other alternatives could include:
Array.prototype.filter()
: Create a new array with only unique elements by filtering out duplicates.Array.prototype.reduce()
: Reduce the array to a single unique element by accumulating unique values and ignoring duplicates.However, these alternatives may not be as efficient or elegant as the Lodash _.uniq()
function or the JavaScript Set
object for large datasets.
In summary, this benchmark compares two popular approaches to remove duplicates from an array: Lodash's _.uniq()
and the JavaScript Set
object. The choice of approach depends on trade-offs between ease of use, efficiency, and external library dependencies.