<script src='https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js'></script>
var l = Array.from(new Set([1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7]));
return l;
var l = [1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7];
return _.uniq(l);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Set + array | |
lodash |
Test name | Executions per second |
---|---|
Set + array | 1886403.8 Ops/sec |
lodash | 5096794.5 Ops/sec |
I'll explain the benchmark and its results in a way that's easy to understand for software engineers of all levels.
Benchmark Overview
The benchmark compares the performance of two approaches:
Array.from(new Set())
)._.uniq()
function from the Lodash library (var l = [1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7]; return _.uniq(l);
).Options Compared
The two options being compared are:
Array.from()
method and the Set
constructor._.uniq()
function from Lodash library to remove duplicates from the array.Pros and Cons of Each Approach
Library and Its Purpose
The Lodash library is a popular utility library that provides a wide range of functions for tasks like string manipulation, array manipulation, and more. In this benchmark, _.uniq()
is used to remove duplicates from the input array.
Special JS Feature or Syntax (Not Applicable in This Case)
There are no special JavaScript features or syntaxes being tested in this benchmark.
Other Alternatives
If you're interested in exploring alternative approaches for removing duplicates from arrays, here are a few options:
Array.prototype.filter()
with an arrow function to remove duplicates.Map
objects to keep track of unique values.For example, the first approach could be implemented as follows:
var l = [];
for (const elem of arr) {
if (!l.includes(elem)) {
l.push(elem);
}
}
return l;
However, this implementation has a time complexity of O(n^2), which is less efficient than using Array.from()
and the Set
constructor.
In summary, the benchmark provides a comparison between two approaches for removing duplicates from arrays: converting to a set and using Lodash's _.uniq()
. The choice of approach depends on the specific requirements of your use case, such as performance, memory usage, and preserving original order.