<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
var elements = [1,2,3,1,2,4,2,3,5,3]
_.uniq(elements)
[new Set(elements)]
elements.filter((v, i, a) => a.indexOf(v) === i)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.uniq | |
set | |
uniq by filter |
Test name | Executions per second |
---|---|
_.uniq | 3442279.2 Ops/sec |
set | 2795562.0 Ops/sec |
uniq by filter | 6238017.0 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
The benchmark measures the performance of three different approaches to find unique elements in an array:
_
notation refers to the Lodash root namespace. The uniq
function takes an array as input and returns a new array with only unique elements.Set
object in JavaScript. When you create a new Set
from an array, it automatically removes duplicates because sets only store unique values. By spreading the original array into a new Set
, we can get a new array with unique elements.filter()
method to create a new array with only unique elements. It works by filtering out elements that are already present in their original index position (i
). The callback function checks if the element is at its first occurrence (by comparing its index with its value's index in the array).Now, let's discuss the pros and cons of each approach:
Set
object.indexOf()
and the additional filtering step.When considering which approach to take, think about the trade-off between performance, conciseness, and maintainability. If you prioritize high performance, _.uniq(elements) might be the best choice. For a more self-contained solution with potentially lower overhead, consider [...new Set(elements)]. The third approach is suitable if readability is your primary concern.
Other alternatives to these approaches include:
Array.prototype.reduce()
and an accumulator object to keep track of unique elements.Array.prototype.map()
and checking for uniqueness in the callback function.For this specific benchmark, it's interesting to see how Lodash's implementation (_.uniq
) outperforms the more lightweight approaches ([...new Set(elements)]
and elements.filter()
). However, the performance difference might not be noticeable in all scenarios.