<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js'></script>
var myArr = Array.from({
length: 16000
}, () => ({ value: Math.floor(Math.random() * 1000) }));
var myCopy = null;
myCopy = _.uniqBy(myArr, 'value');
const itemIdSet = new Set(myArr.map(item => item.value));
const uniqueItems = [];
itemIdSet.forEach(value => {
const uniqueItem = myArr.find(item => item.value === value);
if (uniqueItem) uniqueItems.push(uniqueItem);
});
myCopy = uniqueItems;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash uniqBy | |
Custom uniq array |
Test name | Executions per second |
---|---|
Lodash uniqBy | 3437.6 Ops/sec |
Custom uniq array | 823.6 Ops/sec |
I'll break down the provided benchmark definitions and explain what's being tested, compared options, pros and cons, and other considerations.
Benchmark Definition
The provided benchmark definition is a JSON object that contains the following information:
Name
: A unique name for the benchmark.Description
: An optional description of the benchmark (not used in this case).Script Preparation Code
: A JavaScript code snippet that prepares the data for the benchmark. In this case, it creates an array of 16,000 objects with a random value between 0 and 999.Html Preparation Code
: A script tag that includes the Lodash library version 4.17.21.Individual Test Cases
There are two test cases:
Benchmark Definition
: The code snippet myCopy = _.uniqBy(myArr, 'value');
uses the Lodash library to create a new array with unique elements based on the value property.Benchmark Definition
: The code snippet creates two arrays: itemIdSet
and uniqueItems
. It then iterates over itemIdSet
, finds the corresponding element in myArr
using find()
, and pushes it to uniqueItems
if found.What's being tested?
Both test cases are measuring the performance of unique array creation. The first test case uses a well-known library (Lodash), while the second test case implements a custom solution.
Options compared
The two options being compared are:
uniqBy
function from Lodash to create a new array with unique elements.find()
method.Pros and Cons
Other Considerations
uniqBy
is likely to have better performance due to Lodash's optimization and caching.Browser-specific considerations
The benchmark results are for a specific browser (Chrome 126) and device platform (Desktop). This means that the performance differences between Lodash uniqBy
and the custom implementation might not be apparent in other browsers or devices.