<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var list = [[ 'a', 'b', 'c' ], [ 'b', 'd', 'a', 'e', 'f' ]];
var c = new Set(_.union(list));
var c = new Set(_.flatten(list))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
set from lodash union | |
Set from flatten |
Test name | Executions per second |
---|---|
set from lodash union | 878948.9 Ops/sec |
Set from flatten | 1261891.1 Ops/sec |
Let's break down the benchmark and its test cases.
Benchmark Overview
The benchmark, named "Array immutable union: set from lodash union vs set from lodash flatten", compares two approaches to create an immutable set from an array using Lodash.
Test Cases
There are two test cases:
list
to the _union
function from Lodash, which returns a new set with unique elements.var c = new Set(_.union(...list));
list
to the _flatten
function from Lodash, which returns a new array with all nested arrays flattened.Comparison of Approaches
The two approaches differ in their use of Lodash functions:
_union
function, which takes multiple arguments and returns a new set with unique elements._flatten
function, which takes an array as input and returns a new array with all nested arrays flattened.Pros and Cons of Each Approach
Set from Union:
Pros:
Cons:
Set from Flatten:
Pros:
Cons:
Lodash Library
The benchmark uses Lodash version 4.17.5, which is a popular JavaScript utility library that provides various functions for tasks such as array manipulation, string manipulation, and more. In this case, Lodash's _union
and _flatten
functions are used to create the sets.
JavaScript Features and Syntax
This benchmark does not utilize any special JavaScript features or syntax beyond standard ECMAScript 2015 (ES6+) language features. It only uses JavaScript as a programming language without introducing any specific syntax extensions or experimental APIs.
Alternative Approaches
If you were to implement these test cases using native JavaScript instead of Lodash, you could use the following approaches:
Set
constructor with array methods:var c = new Set(list.map(item => item.join(',')));
This approach requires flattening the nested arrays and converting them to strings before passing them to the Set
constructor.
function union(arrays) {
const result = new Set();
arrays.forEach(array => array.forEach(value => result.add(value)));
return result;
}
var c = new Set(union(list));
This approach requires defining and implementing your own union
function, which can be more complex than using Lodash's _union
function.
Overall, the benchmark provides a useful comparison of two approaches to create immutable sets from arrays using Lodash, showcasing the trade-offs between efficiency, flexibility, and simplicity.