<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js'></script>
var myArr = Array.from({
length: 60000
}, () => ({ 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 | 905.2 Ops/sec |
Custom uniq array | 404.2 Ops/sec |
Let's break down the provided benchmark test cases and explain what is being tested.
Benchmark Purpose
The goal of this benchmark is to measure the performance of two approaches for removing duplicates from an array while preserving the original order: using the lodash.uniqBy
function and a custom implementation.
Options Compared
Two options are compared:
lodash.uniqBy
function, which is a utility function that removes duplicate elements from an array based on a key function. In this case, the key function is 'value'
, meaning that it will remove duplicates based on the value of each element in the array.Set
of unique item IDs and then iterates through the original array to find the corresponding elements for each unique ID.Pros and Cons
Here are some pros and cons for each approach:
Library and Its Purpose
In the benchmark, Lodash is used as a utility library to provide a simple way to remove duplicates from an array. The lodash.uniqBy
function takes two arguments: the input array and a key function that defines how to extract the unique identifier from each element. In this case, the 'value'
key function is used.
Special JS Features or Syntax
There are no special JavaScript features or syntax being used in these benchmark test cases. The code is standard ECMAScript 5+ syntax.
Other Alternatives
If you're interested in exploring alternative approaches to removing duplicates from an array, here are a few options:
Array.prototype.filter()
method and checking for duplicate values using a Set
.Array.prototype.reduce()
method to accumulate unique elements into a new array.These alternatives may have different performance characteristics or trade-offs in terms of code complexity, but they can be interesting to explore if you're looking for more options.