<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/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.concat(b))
var c = new Set([a, b])
var c = new Set(a.concat(b))
var d = Array.from(c)
var c = new Set([a, b])
var d = [c]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.union | |
Set() | |
Set() using array spread | |
Set() convert back to array | |
Set() convert back to array using array spread |
Test name | Executions per second |
---|---|
_.union | 1784350.0 Ops/sec |
Set() | 1177155.5 Ops/sec |
Set() using array spread | 1028556.5 Ops/sec |
Set() convert back to array | 749202.8 Ops/sec |
Set() convert back to array using array spread | 779714.1 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
What is being tested?
The benchmark tests the performance of creating a set from two arrays using different approaches:
_.union
function from the Lodash library (version 4.17.5).Set()
constructor and the concat()
method.Set()
constructor and the array spread syntax ([...a, ...b]
).Array.from(c)
or [...c]
.Array.from(c)
.What options are compared?
The benchmark compares the performance of five different approaches:
_.union
function.Set()
and concat()
.Set()
and array spread syntax ([...a, ...b]
).Array.from(c)
.[...c]
.Pros and cons of each approach:
concat()
method.Other considerations:
_.union
being the fastest (in this specific scenario).[...a, ...b]
) may not be supported in older browsers or environments.Other alternatives:
If you need to create a set from two arrays, consider using:
Set().add()
method with each element individually (not shown in this benchmark).[...new Set(a.concat(b))].
Keep in mind that the best approach depends on your specific use case and requirements.
If you have any further questions or need more clarification, feel free to ask!