<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, 4, 5, 6, 7]
var c = _.union(a, b)
var c = new Set([a, b])
var c = new Set([a, b])
var d = [c]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.union | |
spread to Set() | |
spread to Set() and spread again |
Test name | Executions per second |
---|---|
_.union | 3418568.0 Ops/sec |
spread to Set() | 4079332.5 Ops/sec |
spread to Set() and spread again | 3878396.2 Ops/sec |
Let's break down what's happening in this benchmark.
What is tested:
The benchmark compares the performance of three approaches:
_.union()
method to create a union of two arrays (a
and b
).Set
object from the spread operator (...
) applied to both arrays (a
and b
).Set
object from the spread operator (...
) applied to both arrays (a
and b
), and then spreading that set again.Options compared:
_.union()
method vs.Set
objects created using the spread operator (...
)Set
object, spreading it, and then spreading that result againPros and cons of each approach:
_.union()
method:Set
objects:Library: Lodash
Lodash is a popular JavaScript utility library that provides a collection of functions for common tasks, such as working with arrays, objects, and more. In this case, _.union()
is used to create a union of two arrays, which is what the benchmark is comparing against native JavaScript Set
objects.
Special JS feature/syntax:
The benchmark uses the spread operator (...
) which is a relatively recent addition to the JavaScript language (introduced in ECMAScript 2015). The spread operator allows for creating new arrays or sets by copying elements from an existing array or set. This syntax can be convenient but requires understanding of its usage and potential performance implications.
Other alternatives:
If you're interested in exploring alternative approaches, here are a few options:
Array.prototype.reduce()
to create a union of two arrays.Map
data structure instead of Set
, as it provides similar functionality with additional methods for manipulating keys and values.However, these alternatives may not be as well-optimized or straightforward as the native JavaScript Set
objects and spread operator usage.