<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
var a = [1, 2, 3, 4, 5]
var b = 3
var c = _.union(a, [b])
if(!a.includes(b)){
a.push(b);
}
var c = a;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.union | |
native |
Test name | Executions per second |
---|---|
_.union | 1184645.8 Ops/sec |
native | 3201931.0 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared options, pros/cons, and other considerations.
Benchmark Overview
The benchmark is comparing two approaches:
_
object from Lodash (a utility library) to union an array (_.union
) with a new element.Lodash Library
The _.union()
function is a utility function in Lodash that combines two or more arrays into a single array, removing duplicates. The purpose of this library is to provide a convenient and efficient way to perform common array operations.
Native JavaScript Solution
The native solution uses the includes()
method to check if the new element (b
) is already present in the array (a
). If not, it adds the new element using the push()
method.
Comparison Options
There are two options being compared:
_
object and its _.union()
function.includes()
and push()
).Other Considerations
Html Preparation Code
accordingly.ExecutionsPerSecond
) for each test case. This metric provides an idea of how efficient each approach is in terms of performance.Alternatives
If you want to explore other approaches or alternatives, here are a few options:
Set
: You can use JavaScript's built-in Set
object to union arrays. However, this would require iterating through the array and adding elements to the set.Keep in mind that these alternatives are not necessarily better or worse than the options being compared, but rather provide additional perspectives on how to achieve the same goal (unioning arrays).