<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>
const max2 = 10000000; // 10,000,000 (10 Million)
const arr2 = Array.from({ length: 10000000 }, (_, i) => Math.random() >= 0.5 ? ({ id: i }) : ({ id: Math.floor(Math.random() * 10) + 1 }))
_.uniqBy(arr2, (el) => el.id)
const idsAlreadySeen = new Set();
const uniqArr = arr2.filter(data => {
if (idsAlreadySeen.has(data.id)) {
return false;
}
idsAlreadySeen.add(data.id);
return true;
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash (_.uniqBy) | |
Vanilla code |
Test name | Executions per second |
---|---|
Lodash (_.uniqBy) | 2.4 Ops/sec |
Vanilla code | 0.8 Ops/sec |
The benchmark provided compares two different methods for achieving the same functionality: removing duplicates from an array based on a property (id
) in each object. The two approaches tested are:
_.uniqBy
methodSet
_.uniqBy
Description: The Lodash library provides the uniqBy
function which creates a duplicate-free version of an array by eliminating entries that have the same property value (in this case, id
). The method internally leverages optimization techniques for performance.
Performance: In the benchmark result, this method achieved approximately 2.39 executions per second, indicating a relatively high level of performance.
Pros:
Cons:
Description: This method utilizes the native filter
function combined with a Set
to track already-seen id
s, effectively filtering duplicates from the arr2
array.
Performance: This approach resulted in about 0.83 executions per second, showing that it is notably slower than the Lodash version in this particular test.
Pros:
Cons:
Set
and additional logic inside the filter
function can make the code less readable than the Lodash approach.Performance Context: The performance results may vary across different browsers and environments, so it's crucial to consider the target audience when deciding which method to use.
Code Readability and Maintenance: Choosing between a library and vanilla JavaScript often depends on the project requirements, team familiarity, and the importance of code readability versus performance.
Alternatives:
reduce
or other Data Structures (e.g., Map) could also be explored for deduplication tasks. Each alternative might offer different trade-offs in terms of performance and code clarity.In conclusion, while Lodash's _.uniqBy
offers better performance and readability in this specific benchmarking scenario, vanilla JavaScript provides a lightweight alternative without external dependencies. The best choice often depends on specific project needs and constraints.