<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)]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.union | |
Set() | |
Set() convert back to array |
Test name | Executions per second |
---|---|
_.union | 1410148.8 Ops/sec |
Set() | 1886672.9 Ops/sec |
Set() convert back to array | 1512137.1 Ops/sec |
Let's break down the provided benchmark and its test cases.
Benchmark Overview
The benchmark, hosted on MeasureThat.net, compares three approaches to union two arrays in JavaScript:
lodash
library's _union
function (Lodash _.union)Set()
constructorLibrary and Purpose
The lodash
library is a popular JavaScript utility library that provides various functional programming helpers, including data manipulation functions like _union
. In this benchmark, it's used to implement the _union
function.
Test Cases and Approaches
Here are the individual test cases with their descriptions:
lodash
library's _union
function. It takes two arrays as input (a
and b
) and returns a new array containing all unique elements from both arrays.Set()
constructor, passing a
and b
as arguments. Sets in JavaScript are unordered collections of unique values, making them ideal for this use case. The test case measures the performance of creating a new Set from two arrays.Set()
constructor, passing a
and b
as arguments, just like in the previous test case. However, instead of measuring the performance of the Set creation directly, it measures the performance of converting the resulting Set back to an array.Comparison and Pros/Cons
Here's a comparison of the three approaches:
lodash
is a widely used and well-maintained library, so it's likely that its implementation is optimized for performance.Special Considerations
This benchmark does not specifically target any special JavaScript features or syntax, so it should be relevant to most software engineers familiar with JavaScript basics.
Alternatives
Other approaches to union two arrays in JavaScript include:
concat()
and checking for duplicates using indexOf()
: This approach is simple but might be less efficient due to the overhead of function calls and potential duplicate checks.Keep in mind that this benchmark is specific to JavaScript and its Set data structure. The results may not directly translate to other programming languages or data structures.