<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)]
_.forEach(b, (val) => {
if (!a.includes(val)) a.push(val);
})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.union | |
Set() convert back to array | |
include |
Test name | Executions per second |
---|---|
_.union | 3151054.0 Ops/sec |
Set() convert back to array | 3788618.5 Ops/sec |
include | 2671984.0 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares three approaches to achieve similar results:
_.union()
function[...]
)Options Compared
The benchmark is testing three options, each with its pros and cons:
Library: Set()
The Set()
data structure is a native JavaScript API that stores unique values. In this benchmark, it's used to create a set from the arrays a
and b
, and then converted back to an array using the spread operator ([...]
). The library is not explicitly mentioned in the JSON provided, but Set() is a widely available and well-documented JavaScript feature.
Special JS Feature/Syntax: Spread Operator
The spread operator ([...]
) is a relatively recent addition to JavaScript, introduced in ECMAScript 2015 (ES6). It allows creating new arrays by spreading elements from an existing array or other iterable data structure. In this benchmark, the spread operator is used to convert the Set back into an array.
Other Alternatives
If you're interested in exploring alternative approaches, consider:
Array.from()
and Set.prototype.has()
: Another way to create a set from arrays and check for membership.Underscore.js
or Ramda
).These alternatives might offer trade-offs in terms of performance, readability, or additional dependencies, so it's essential to evaluate them based on your specific use case and requirements.
Keep in mind that this benchmark is primarily focused on comparing the performance of these three approaches. If you're interested in exploring more efficient solutions or optimizations, there may be opportunities for further investigation.