<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
const a = [1, 2, 3, 4, 5]
const b = [3, 4, 5, 6, 7]
const c = _.union(a, b)
const setA = new Set(a)
const setB = new Set(b)
const c = setA.union(setB)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash union | |
new Set() union |
Test name | Executions per second |
---|---|
Lodash union | 3862328.5 Ops/sec |
new Set() union | 2896312.2 Ops/sec |
The benchmark you provided focuses on comparing two different approaches for computing the union of two arrays in JavaScript: one using the Lodash library and the other utilizing the native JavaScript Set
object.
Lodash Union Test Case
const c = _.union(a, b);
This code uses Lodash’s _.union
function to find the unique elements from two arrays a
and b
. Lodash handles the uniqueness internally and combines the two arrays efficiently.New Set() Union Test Case
const setA = new Set(a);
const setB = new Set(b);
const c = setA.union(setB);
This attempts to create a Set
from both arrays a
and b
and calls a non-existent union()
method. The correct approach would involve merging the sets manually. For example:const c = [...setA, ...setB];
Using Set
is beneficial because it inherently handles uniqueness, ensuring that duplicates are removed.Sets
are part of the standard JavaScript specification, so no external libraries are required.Set
does not provide a built-in union
method; users must implement their logic to combine sets, effectively rising complexity.From the benchmark results, we can observe the execution speed of both approaches on Chrome 131.
filter()
in conjunction with includes()
.Overall, when performing operations involving unions or array manipulations, it is essential to consider the complexity of the operation, the need for dependencies, maintainability of the code, and testing for performance in your specific environment.