<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 as = new Set(a)
var bs = new Set(b)
var c = _.union(a, b)
var c = new Set(a, b)
var c = new Set(a, b)
var d = Array.from(c)
var c = as.union(bs)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.union | |
Set() | |
Set() convert back to array | |
Set union |
Test name | Executions per second |
---|---|
_.union | 5411672.0 Ops/sec |
Set() | 15265948.0 Ops/sec |
Set() convert back to array | 11734937.0 Ops/sec |
Set union | 12829269.0 Ops/sec |
The benchmark you've provided tests the performance of merging two arrays to produce a unique set of elements using different methods in JavaScript. It contrasts Lodash's _.union
method with the native JavaScript Set object, which is a built-in feature for storing unique values. Here’s a breakdown of what’s being compared and the implications of each approach:
Lodash's _.union
:
var c = _.union(a, b)
_.union
Native JavaScript Set
:
var c = new Set(a, b)
Set()
new Set([...a, ...b])
).Set Convert Back to Array:
var c = new Set(a, b); var d = Array.from(c)
Set() convert back to array
Array.from()
. This is a common pattern when you want unique values in array form.Set Union:
var c = as.union(bs)
Set union
.union
method, and this code would throw an error unless it were extended by the developer.The results show the number of executions per second for each method when tested in the same environment (Chrome 131 on Windows):
Lodash _.union
:
Native Set
:
Set Convert Back to Array:
Set Union:
Set
lacks this method; would require additional implementation.Choosing between these approaches largely depends on your project's requirements and the data structures involved. If performance is critical and you are working in an environment that supports ES6, using the native Set is advisable. On the other hand, if you prioritize code readability, especially in projects where Lodash is already being utilized, using _.union
might be acceptable despite its slower performance.
Other alternatives to these methods include:
In summary, the best approach depends on your performance needs, the size of the datasets involved, and your codebase's existing dependencies and style preferences.