<script src='https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js'></script>
var l = new Set([1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7]);
return Array.from(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 |
Test name | Executions per second |
---|---|
Set | 4002984.2 Ops/sec |
Array | 10295631.0 Ops/sec |
I'll break down the provided benchmark and explain what's being tested, compared options, pros and cons, and other considerations.
Benchmark Overview
The benchmark compares two approaches to remove duplicates from an array:
Array.from()
and a regular Set (Set Approach)uniq
function (Lodash Approach)Set Approach (Individual Test Case)
var l = new Set([1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7]);\r\nreturn Array.from(l);
In this test case:
7
).Array.from()
function is used to convert the Set to an array.Lodash Approach (Individual Test Case)
var l = [1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7];\r\nreturn _.uniq(l);
In this test case:
7
).uniq
function is used to remove duplicates from the array.Comparison and Pros/Cons
Both approaches achieve similar results: removing duplicates from an array. However, there are differences in their behavior:
Array.from()
and Set
). Lodash Approach uses a custom implementation, which might incur additional overhead.Other Considerations
Alternatives
For removing duplicates from an array:
Array.from()
and a regular Set:var arr = [1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7];
var uniqueArr = Array.from(new Set(arr));
filter()
method:var arr = [1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7];
var uniqueArr = arr.filter((val, idx) => {
return arr.indexOf(val) === idx;
});
Keep in mind that these alternatives might not be as efficient or feature-rich as the Set Approach or Lodash Approach.
When to use each approach: