<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>
var arr1 = Array.from({length: 1000000}, (v, i) => ({ name: i }));
var concatArr = [].concat(arr1, { name: 999999 });
let result = null;
function myUniqBy (arr, name) {
let result = []
let obj = {}
for (let i of arr) {
if (!obj[i[name]]) {
result.push(i)
obj[i[name]] = i
}
}
return result
}
result = _.uniqBy(concatArr, 'name');
result = myUniqBy(concatArr, 'name');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.uniqBy | |
myUniqBy |
Test name | Executions per second |
---|---|
_.uniqBy | 12.6 Ops/sec |
myUniqBy | 25.4 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark is comparing two functions: _.uniqBy
from Lodash and a custom function called myUniqBy
. Both functions are designed to remove duplicates from an array based on a specific property.
Function Comparison
In the provided JSON, we see two test cases:
_.uniqBy(concatArr, 'name')
: This tests the original implementation of _.uniqBy
from Lodash.myUniqBy(concatArr, 'name')
: This tests the custom implementation called myUniqBy
.Functionality Comparison
Both functions take an array and a property name as input. They iterate through the array, and for each element, they check if the corresponding value in the object (created by hashing the original value) is already present. If not, they add the element to the result array.
Here's a high-level comparison of the two approaches:
_.uniqBy
Pros:
Cons:
myUniqBy
Pros:
Cons:
Library: _.uniqBy (Lodash)
.uniqBy
is a utility function from the Lodash library, which provides a convenient way to remove duplicates from an array based on a specific property. The original implementation of _.uniqBy
likely uses a combination of hashing and iteration to achieve performance optimization.
Special JavaScript Features or Syntax
There are no special JavaScript features or syntax mentioned in the benchmark code.
Other Alternatives
If you prefer not to use Lodash, here are some alternatives:
Keep in mind that this benchmark is testing the performance of these two specific implementations. Depending on your project's requirements and constraints, you may need to choose between using an existing library (like Lodash) or implementing something custom.