<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.5/lodash.min.js"></script>
var itemsCount = 1e2;
var items = Array.from({ length: itemsCount }, () => Math.floor(Math.random() * itemsCount));
items.reduce((list, item) => list.indexOf(item) > -1 ? list : [list, item], []);
_.uniq(items)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Javascript Array.reduce/Array.indexOf | |
Lodash Uniq |
Test name | Executions per second |
---|---|
Javascript Array.reduce/Array.indexOf | 91552.8 Ops/sec |
Lodash Uniq | 268247.0 Ops/sec |
Let's break down the provided benchmark and its test cases.
Benchmark Overview
The benchmark is designed to compare the performance of two approaches for creating an array with unique values: Array.reduce
combined with Array.indexOf
(using JavaScript) and Lodash's uniq
function.
Script Preparation Code
The script preparation code generates a random array of 100 unique integers using the Array.from
method. This array is used as input for both test cases.
var itemsCount = 1e2; // 100
var items = Array.from({ length: itemsCount }, () => Math.floor(Math.random() * itemsCount));
Html Preparation Code
The HTML preparation code includes the Lodash library, which is used in one of the test cases.
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.5/lodash.min.js"></script>
Test Cases
There are two test cases:
This test case uses the reduce
method in combination with Array.indexOf
. The idea is to iterate over the array and add each item to the result array if it's not already present.
items.reduce((list, item) => list.indexOf(item) > -1 ? list : [...list, item], []);
Pros:
Cons:
indexOf
method can lead to a linear search in the worst case (when an item is not found), resulting in a time complexity of O(n).uniq
.This test case uses Lodash's uniq
function to create an array with unique values.
_.uniq(items);
Pros:
Cons:
Other Considerations
ExecutionsPerSecond
value indicates the number of times each test case was executed per second, which can affect the overall performance measurement.Alternative Approaches
Other approaches to create an array with unique values could include:
new Set(items).values();
Keep in mind that the performance of these alternatives might vary, and it's essential to test and benchmark them to determine their suitability for your specific use case.