<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 | |
Set() | |
Set() convert back to array |
Test name | Executions per second |
---|---|
_.union | 3167891.0 Ops/sec |
Set() | 4007660.2 Ops/sec |
Set() convert back to array | 3793653.5 Ops/sec |
Overview of the Benchmark
The provided benchmark compares the performance of three approaches for performing set operations in JavaScript:
_.union
functionadd()
method to add elements from two arrays[...]
)Library: Lodash
Lodash is a popular JavaScript utility library that provides a set of reusable functions for common tasks, including array manipulation. In this benchmark, Lodash's _.union
function is used to compare its performance with native Set operations.
The _.union
function takes two arrays as input and returns a new array containing all unique elements from both arrays.
Native Set Operations
Creating a new Set object allows you to efficiently store and look up elements. The add()
method is used to add elements to the set, which has an average time complexity of O(1).
Converting a Set back to an array using the spread operator ([...]
) has a time complexity of O(n), where n is the number of elements in the set.
Performance Comparison
The benchmark results show that:
[...]
) (option 3) is slower than option 2 but still relatively fast, with an average execution speed of approximately 16,378,910.0 executions per second._.union
function (option 1) is the slowest approach, with an average execution speed of approximately 3,167,911.0 executions per second.Pros and Cons
Here are some pros and cons for each approach:
add()
method_.union
functionOther Alternatives
If you're looking for alternative approaches, consider the following:
and
Set**: This approach combines the benefits of options 2 and 3 by creating a new Set object and then concatenating an array of values using
concat()`. However, it may still be slower than option 2.In conclusion, when performing set operations in JavaScript, consider using native Set objects (option 2) for optimal performance. If you prefer a more functional programming style or need to handle large datasets efficiently, explore alternative approaches like Array.prototype.reduce() or using an array with a Set object.