<script src='https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js'></script>
var arr = [5,1,3,7,9,2,11];
var mySet = new Set(arr);
mySet.add(12);
mySet.add(12);
mySet.add(5);
mySet.add(17);
mySet.add(1);
mySet.add(11);
return arr;
arr = _.uniq(arr.push(12));
arr = _.uniq(arr.push(12));
arr = _.uniq(arr.push(5));
arr = _.uniq(arr.push(17));
arr = _.uniq(arr.push(1));
arr = _.uniq(arr.push(12));
return arr;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
set | |
uniq |
Test name | Executions per second |
---|---|
set | 6824063.0 Ops/sec |
uniq | 7982080.5 Ops/sec |
Let's break down the provided benchmark and its test cases.
Benchmark Overview
The benchmark compares two JavaScript methods for removing duplicates from an array: lodash uniq
(from the Lodash library) and the built-in Set
object in JavaScript.
Options Compared
The two options are:
Set
object, but with additional features like handling null and undefined values, and preserving the original order of elements.Pros and Cons
Library: Lodash
Lodash is a popular JavaScript utility library that provides a wide range of functions for tasks like array manipulation, object creation, and more. The uniq
function in particular is designed to remove duplicate values from an array while preserving the original order.
In the benchmark, Lodash uniq is used to create a set-like data structure with unique values, allowing us to compare its performance with the built-in Set object.
Special JS Feature: Rest Parameter
The test cases use the rest parameter syntax (arr.push(12)
) to dynamically add elements to an array. This feature allows you to pass a variable number of arguments to a function, which is useful for tasks like the benchmark where we need to add multiple values to an array.
Benchmark Preparation Code
The preparation code sets up the test data and environment:
var arr = [5,1,3,7,9,2,11];
: Creates an initial array with duplicate values.var mySet = new Set(arr);
: Creates a Set object from the array, which is used as a baseline for Lodash uniq.Individual Test Cases
The two test cases are:
Latest Benchmark Result
The latest benchmark result shows that the uniq
test (using Lodash) performs slightly better than the set
test (using the built-in Set object), with approximately 115,800 more executions per second. However, this difference is relatively small, suggesting that both methods are suitable for most use cases.
Other Alternatives
Some other alternatives to removing duplicates from an array in JavaScript include:
every()
method: arr.filter((element) => arr.indexOf(element) === -1)
filter()
method: arr.map((element) => element).filter((element, index, self) => self.indexOf(element) === index)
reduce()
method: arr.reduce((acc, element) => acc.includes(element) ? acc : [element], [])