<script src='https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js'></script>
const res = Array.from(new Set([1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7]));
return res;
var res = _.uniq([1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7]);
return res;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Set | |
Array |
Test name | Executions per second |
---|---|
Set | 1323563.0 Ops/sec |
Array | 3765141.2 Ops/sec |
Let's dive into the explanation of the provided JSON benchmark.
Benchmark Definition
The benchmark measures the performance of two approaches to remove duplicates from an array:
Set
data structure to remove duplicates from the array. The Set
object in JavaScript is a collection of unique values, and when you convert an array to a set using Set()
, it automatically removes any duplicate elements._uniq()
function, which removes duplicate elements from an array.Options Compared
The two options compared in this benchmark are:
Array.from(new Set([array]))
_uniq(array)
These approaches have different performance characteristics, pros, and cons:
Array.from(new Set([array]))
:Set
data structure. It also has better cache locality, as the resulting array is contiguous in memory._uniq(array)
:_uniq()
function is implemented in C++ and optimized for performance. It also avoids the overhead of creating a new set object.Library (Lodash)
The Set
data structure is a built-in JavaScript feature, but it's only available in ECMAScript 2015 and later standards. In earlier versions of JavaScript, you would need to use libraries like Lodash or underscore.js to implement a similar functionality.
JavaScript Features/Syntax
There are no special JavaScript features or syntax used in this benchmark. It's purely functional programming with JavaScript.
Other Alternatives
If you're interested in exploring other approaches, here are some alternatives:
Array.prototype.filter()
: You can use the filter()
method to remove duplicates from an array, like this: [...new Set(array)].filter((v, i) => array.indexOf(v) === i)
Array.prototype.reduce()
: Another approach is to use the reduce()
method to accumulate unique elements into a new array: array.reduce((acc, v) => acc.includes(v) ? acc : [...acc, v], [])
Set
implementation: If you're using ECMAScript 2015 or later, you can use the native Set
data structure directly.Keep in mind that these alternatives may have different performance characteristics and overhead compared to the two options being benchmarked.