<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
var firstEqual = [];
var secondEqual = [];
for (var i=0; i<=10000; i++) {
firstEqual.push(i);
secondEqual.push(i);
}
var elements = [firstEqual, secondEqual];
_.uniq(elements)
[new Set(elements)]
elements.filter((v, i, a) => a.indexOf(v) === i)
Array.from(new Set(elements))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.uniq | |
set with spread | |
uniq by filter | |
set with array.from |
Test name | Executions per second |
---|---|
_.uniq | 1052.8 Ops/sec |
set with spread | 1407.1 Ops/sec |
uniq by filter | 9.3 Ops/sec |
set with array.from | 1256.1 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Overview
The provided benchmark measures the performance of different methods to find unique elements in an array of 10,000 items. The script preparation code creates two arrays, firstEqual
and secondEqual
, each populated with 10,000 consecutive integers from 0 to 9,999. These arrays are then merged into a single array called elements
.
Comparison of Methods
The benchmark compares four methods:
_.uniq
: This method uses the Lodash library to find unique elements in the array.[...new Set(elements)]
): This method converts the array into a set and then spreads its elements back into an array, effectively removing duplicates.elements.filter((v, i, a) => a.indexOf(v) === i)
): This method iterates over the array, filtering out elements that have already been encountered (i.e., those with duplicate indices).Array.from()
to create an array from a set.Pros and Cons of Each Method
_._uniq
:[...new Set(elements)]
):elements.filter((v, i, a) => a.indexOf(v) === i)
):filter()
which might incur additional overhead.Other Considerations
When choosing a method for finding unique elements in an array, consider factors such as:
In general, methods like Lodash's _._uniq
and Set-based approaches are well-suited for most use cases due to their performance and conciseness. However, filtering by index might be a better choice if memory is a concern, while Array.from(new Set(elements)) provides a middle ground between the two.
Library: Lodash
Lodash is a popular JavaScript library that provides a wide range of utility functions for data manipulation, string manipulation, and more. The _._uniq
method is one of its many optimizations for finding unique elements in an array.
JavaScript Feature/ Syntax: None
There are no special JavaScript features or syntax used in this benchmark, making it accessible to developers with varying levels of expertise in the language.
I hope this explanation helps you understand the provided benchmark and the methods being compared!