<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var myArr = Array.from({
length: 16000
}, () => ({ someData: 123, value: Math.floor(Math.random() * 1000) }));
var myCopy = null;
myCopy = _.uniqBy(myArr, 'value').map(({ value }) => value);
myCopy = [new Map(myArr.map((el) => [el.value, el])).values()];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash uniqBy | |
new Map() Destructuring |
Test name | Executions per second |
---|---|
Lodash uniqBy | 3872.2 Ops/sec |
new Map() Destructuring | 1766.6 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and their pros and cons.
What's being tested:
Two individual test cases are being compared:
uniqBy
function[...new Map()]
)The test case uses an array myArr
with 16,000 elements, each containing two properties: someData
and value
. The purpose of this setup is to create a scenario where both functions are called repeatedly, allowing for a fair comparison.
Options compared:
uniqBy
[...new Map()]
)Library: Lodash
Lodash is a popular utility library for JavaScript. uniqBy
is one of its functions, designed to remove duplicate elements from an array based on the value of a specific property. In this benchmark, it's used to compare its performance with the native JavaScript solution using Map destructuring.
Special JS feature or syntax:
There are no special JavaScript features or syntaxes being tested in this benchmark. The focus is solely on comparing the performance of two different approaches.
Benchmark preparation code
The preparation code sets up an array myArr
and initializes a variable myCopy
to null, which will be used by both test cases. The HTML preparation code includes the Lodash library from a CDN.
Individual test cases
Each test case defines a specific benchmarking scenario:
uniqBy
function from Lodash to remove duplicates from myArr
based on the value
property, and then maps over the resulting array using destructuring.myArr
, extracts the values, and then uses the spread operator to convert it into an array.Latest benchmark result
The provided results show the execution count per second for each test case on a Chrome 111 browser running on a Mac OS X 10.15.7 system. The "Lodash uniqBy" test outperforms the native Map destructuring solution, but with a close margin.
Other alternatives:
Other alternatives to comparing performance in this benchmark could be:
Set
, Filter()
)reduce()
function