<script src='https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js'></script>
var arr = ['Batman', 'Dr. Doom', null, 'Iron Man', 'Rorschach', 'Captain America', 'J. Jonah Jameson', 'The Mekon', null, '', null, '', 'Scott Pilgrim', 'Batman', 'Dr. Doom', 'Iron Man', 'Rorschach', 'Captain America', 'J. Jonah Jameson', 'The Mekon', 'Scott Pilgrim', 1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7];
var u = new Set(arr);
return u;
var u = _.uniq(arr)
return u;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Set | |
uniq |
Test name | Executions per second |
---|---|
Set | 473860.8 Ops/sec |
uniq | 423225.4 Ops/sec |
Let's break down the provided JSON to understand what's being tested.
Benchmark Definition: The benchmark tests two approaches to get unique items from an array:
Set
data structure ( Benchmark Definition: "var u = new Set(arr);\r\nreturn u;" )uniq
function ( Benchmark Definition: "var u = _.uniq(arr)\r\nreturn u;" )What is tested?
The benchmark compares the performance of these two approaches in two aspects:
Options compared:
uniq
functionPros and cons of each approach:
uniq
functionLibrary:
The uniq
function is part of the Lodash library, a popular JavaScript utility library that provides a wide range of functions for various tasks, such as array manipulation, string manipulation, and more.
Special JS feature or syntax:
None mentioned in this benchmark. The use of Set
data structure is a built-in JavaScript feature, while the uniq
function from Lodash is a specific implementation of an algorithm to remove duplicates from an array.
Other alternatives: If you want to explore other approaches, here are a few options:
Array.prototype.filter()
method and Array.from()
: const u = Array.from(arr).filter((value, index, self) => self.indexOf(value) === index);
Array.prototype.reduce()
method: const u = arr.reduce((unique, value) => { if (!unique.has(value)) unique.add(value); return unique; }, new Set());
These alternatives may have different performance characteristics and trade-offs compared to the Set data structure and Lodash's uniq
function.