<script src='https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js'></script>
var arr = new Array(10_000).fill(1).map(() => Math.round(Math.random() * 20))
return [new Set(arr)]
return _.uniq(arr);
return Array.from( new Set(arr) );
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Spread | |
use lodash | |
Array.from |
Test name | Executions per second |
---|---|
Spread | 8101.0 Ops/sec |
use lodash | 7939.3 Ops/sec |
Array.from | 8083.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition
The benchmark is designed to compare three approaches for removing duplicate values from an array:
Array.from(new Set(arr))
: This method creates a new set from the input array and then converts it back to an array using Array.from()
.uniq()
function from the Lodash library: This function takes an array as input and returns a new array with duplicate values removed....
) with new Set(arr)
: This method creates a new set from the input array and then uses the spread operator to convert it back to an array.Options Compared
The three approaches are compared in terms of performance, which is measured by the number of executions per second (ExecutionsPerSecond).
Pros and Cons
Other Considerations
The benchmark is likely testing for performance, but it's also worth considering the readability and maintainability of each approach. For example, using Array.from(new Set(arr))
may require more code and setup compared to using _.uniq()
from Lodash.
Library: Lodash
Lodash (also known as underscore) is a popular JavaScript library that provides a collection of utility functions for tasks such as data manipulation, array operations, and string manipulation. The uniq()
function is one of the many useful utilities provided by Lodash.
Special JS Feature/Syntax
There doesn't appear to be any special JavaScript features or syntax used in this benchmark beyond what's necessary for the three approaches being compared. If there were any special features or syntax, I'd be happy to explain them!
Alternatives
Other alternatives for removing duplicates from an array might include:
filter()
and checking for duplicate values.However, these alternatives may not be as efficient or concise as the three approaches being compared in this benchmark.