<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)
elements.filter(function filter(element) {
return element in this ? false : ((this)[element] = true);
}, Object.create(null));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.uniq | |
set | |
uniq by filter | |
uniq by qiankun |
Test name | Executions per second |
---|---|
_.uniq | 7488823.0 Ops/sec |
set | 4558792.0 Ops/sec |
uniq by filter | 11005329.0 Ops/sec |
uniq by qiankun | 3121433.8 Ops/sec |
Let's dive into the provided benchmark definition and test cases.
What is being tested?
The provided benchmark tests four different approaches to find unique elements in an array:
_.uniq
(Lodash): This function uses a Set data structure to keep track of unique elements.[...new Set(elements)]
: This approach converts the array to a Set, which automatically removes duplicates.elements.filter((v, i, a) => a.indexOf(v) === i)
: This approach uses the indexOf
method to check if an element is present in the original array at the same index it appears in the new array.elements.filter(function filter(element) { ... })
: This approach uses a closure (an anonymous function) to keep track of unique elements.Options compared
The four approaches are compared in terms of their execution speed, with the goal of finding the fastest way to find unique elements in an array.
Pros and Cons of each approach:
_.uniq
(Lodash):[...new Set(elements)]
:elements.filter((v, i, a) => a.indexOf(v) === i)
:elements.filter(function filter(element) { ... })
:Library description
Lodash is a JavaScript library that provides a lot of useful functions for common tasks, such as array manipulation (_.uniq
), string manipulation, and more.
Special JS feature or syntax
None of the test cases use special JavaScript features or syntax. They are all basic array operations.
Other alternatives
Some other approaches to find unique elements in an array include:
Array.prototype.reduce()
lodash-es
(a more modern and minimalist version of Lodash)These alternative approaches may have their own pros and cons, but are not tested in the provided benchmark.
I hope this explanation helps! Let me know if you have any further questions.