<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var smalldata = [1,2,3,4,5,'ok','abc','def',null,undefined,1,2,3,'ok'];
var bigdata = [1,2,3,4,5,'ok','abc','def',null,undefined,1,2,3,'ok',1,2,3,4,5,'ok','abc','def',null,undefined,1,2,3,'ok',1,2,3,4,5,'ok','abc','def',null,undefined,1,2,3,'ok',1,2,3,4,5,'ok','abc','def',null,undefined,1,2,3,'ok',1,2,3,4,5,'ok','abc','def',null,undefined,1,2,3,'ok',1,2,3,4,5,'ok','abc','def',null,undefined,1,2,3,'ok',1,2,3,4,5,'ok','abc','def',null,undefined,1,2,3,'ok',1,2,3,4,5,'ok','abc','def',null,undefined,1,2,3,'ok',1,2,3,4,5,'ok','abc','def',null,undefined,1,2,3,'ok'];
var uniq = (arr) => {
var dups = new Set();
return arr.filter((v) => {
if (dups.has(v)) {
return false;
}
dups.add(v);
return true;
});
};
var uniqset = (arr) => [ (new Set(arr))];
_.uniq(smalldata);
_.uniq(bigdata);
uniq(smalldata);
uniq(bigdata);
uniqset(smalldata);
uniqset(bigdata);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash/uniq | |
filter+set | |
array→set→array |
Test name | Executions per second |
---|---|
lodash/uniq | 154580.6 Ops/sec |
filter+set | 290562.5 Ops/sec |
array→set→array | 325574.5 Ops/sec |
Let's break down the benchmark and explain what's being tested, the options compared, their pros and cons, and other considerations.
Benchmark Overview
The benchmark compares three approaches to remove duplicate elements from an array:
uniq
functionfilter
, Set
, and array→set→array
methods (let's call it "filter+set")uniqset
) followed by a set creation and then another spread operation (array→set→array
)Test Cases
The benchmark consists of three test cases:
uniq
function with two datasets: smalldata
(a small array) and bigdata
(a large array).filter
, Set
, and array→set→array
methods with both smalldata
and bigdata
.smalldata
and bigdata
.Options Compared
The three approaches have different characteristics:
uniq
function:Library
In this benchmark, Lodash is used as a library. Lodash provides a high-quality implementation of various utility functions, including uniq
. The use of Lodash allows for a fair comparison with custom implementations.
Special JS Features
There are no special JavaScript features or syntax used in this benchmark. All implementations rely on standard JavaScript methods and data structures.
Other Considerations
When choosing an implementation, consider the following factors:
uniq
function from Lodash might be a better choice due to its optimized implementation.Alternatives
If you're looking for alternative implementations or libraries, consider the following options:
Set.from()
from modern browsers or libraries like fast-set
provide efficient set creation methods.filter+set
, can be optimized for specific use cases.Keep in mind that each implementation has its strengths and weaknesses. The choice ultimately depends on your project's requirements and your team's expertise.