<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var testFiles = _.range(_.random(100)).map(x => ({
id: _.random(1, 10),
}));
_.uniqBy(testFiles,"id")
testFiles.reduce((accumulator, item) => {
if (item === null) {
return accumulator;
}
const keyExist = accumulator.some((i) => i["id"] === item["id"]);
return keyExist === true ? accumulator : [accumulator, item];
}, []);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash | |
Reduce |
Test name | Executions per second |
---|---|
Lodash | 1051151.5 Ops/sec |
Reduce | 507165.0 Ops/sec |
Overview of the Benchmark
The provided JSON represents a JavaScript microbenchmark created on MeasureThat.net. The benchmark compares the performance of two approaches for filtering an array of objects by a key: Lodash's uniqBy
function and the built-in reduce
method.
Options Compared
Two options are compared:
uniqBy
: This is a utility function from the Lodash library that takes an array of objects and a key as input, and returns a new array with duplicate entries removed based on the specified key.reduce
method: This is a built-in JavaScript method that applies a reduction function to each element in an array, reducing it to a single output value.Pros and Cons
uniqBy
Pros:
Cons:
reduce
methodPros:
Cons:
Library: Lodash
Lodash is a popular JavaScript utility library that provides a wide range of functions for common tasks, such as array manipulation, object transformation, and more. In this benchmark, uniqBy
is used to filter an array of objects by a key.
Test Case Analysis
The test cases compare the performance of each approach:
uniqBy
: The uniqBy
function is called with the testFiles
array and the "id"
key as arguments.reduce
method: The reduce
method is implemented using a custom reduction function that checks for duplicate keys in the accumulator.Device-Specific Feature: iOS 17
The benchmark result shows a difference in performance between the two approaches on an iOS 17 device, with Lodash's uniqBy
outperforming the built-in reduce
method. This suggests that there may be some underlying differences in how the JavaScript engine optimizes or executes these two functions on this specific platform.
Alternative Approaches
Other alternatives to compare in this benchmark could include:
filter
or every
uniqBy
with the built-in reduce
method on different devices (e.g., desktop vs. mobile)