<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
var elements = [8,9,34,12,4,2,1,5,7,2,8,1,25,7,1,2,3,1,2,4,2,3,5,3,9,34,12,4,2,1,5,7,2,8,1,25,7,1,2,3,1,2,4,2,39,34,12,4,2,1,5,7,2,8,1,25,7,1,2,3,1,2,4,2,39,34,12,4,2,1,5,7,2,8,1,25,7,1,2,3,1,2,4,2,39,34,12,4,2,1,5,7,2,8,1,25,7,1,2,3,1,2,4,2,39,34,12,4,2,1,5,7,2,8,1,25,7,1,2,3,1,2,4,2,39,34,12,4,2,1,5,7,2,8,1,25,7,1,2,3,1,2,4,2,3,7,2,8,1,25,7,1,2,3,1,2,4,2,37,2,8,1,25,7,1,2,3,1,2,4,2,37,2,8,1,25,7,1,2,3,1,2,4,2,37,2,8,1,25,7,1,2,3,1,2,4,2,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 | 559074.0 Ops/sec |
set | 400883.9 Ops/sec |
uniq by filter | 294067.8 Ops/sec |
Measuring JavaScript performance is an essential task in software development, and MeasuringThat.net provides a useful platform for it.
The provided benchmark tests the uniqueness of elements in an array using three different approaches:
uniq
function from the Lodash library, which is a utility function that returns a new array with unique values.Set
object from the input array and then converts it back to an array using the spread operator ([...]
). The Set
data structure automatically removes duplicates, making this approach efficient.Set
object can be memory-intensive for large arrays. Additionally, this approach may not work as expected if the input array contains non-unique elements that are considered equal (e.g., due to a custom equality check).filter
method to create a new array with only unique elements. It achieves this by comparing each element's index in the original array (a.indexOf(v)
) to its value (v
). If they're equal, it means the element is unique.Set
approach due to the extra function calls involved.All three approaches have their strengths and weaknesses. The Lodash library's uniq
function is convenient but might introduce some overhead. The Set
approach is fast and simple, but it requires memory for the temporary set data structure. The filter-based approach is another efficient option with native JavaScript functions, but it may require more complex logic.
Additional considerations:
Other alternatives:
Array.prototype.reduce()
method along with a custom equality check function to remove duplicates.