<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/immutability-helper@2.7.0/index.min.js"></script>
const set1_Immutable = new Immutable.Set(Array.from(Array(100).keys()));
const set2_Immutable = new Immutable.Set(Array.from(Array(1000).keys()));
const result = set1_Immutable.union(set2_Immutable)
const set1_JS = new Set(Array.from(Array(100).keys()));
const set2_JS = new Set(Array.from(Array(1000).keys()));
const result = new Set([set1_JS, set2_JS])
const set1_JS = new Set(Array.from(Array(100).keys()));
const set2_JS = new Set(Array.from(Array(1000).keys()));
const result = new Set(Array.from(set1_JS).concat(Array.from(set2_JS)))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Immutable.Set union | |
Convert JS Set to array, construct new Set | |
Array.from, construct new Set |
Test name | Executions per second |
---|---|
Immutable.Set union | 10014.9 Ops/sec |
Convert JS Set to array, construct new Set | 19342.0 Ops/sec |
Array.from, construct new Set | 20631.1 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares three approaches to performing set operations in JavaScript:
Options Compared
Here are the options being compared:
set1_Immutable
and set2_Immutable
, and then performs a union operation on them.Array.from()
, creates two new empty Sets, and then uses the spread operator (...
) to merge the two arrays into a single Set.Array.from()
to convert one of the input Sets to an array, concatenates that array with another array created from the second input Set using Array.from()
, and then creates a new Set from the concatenated array.Pros and Cons
Here are some pros and cons of each approach:
Array.from()
to convert one of the input Sets to an array, which is faster than converting both sets to arrays, and then concatenates that array with another array created from the second input Set. However, it still requires creating multiple intermediate arrays.Library Usage
The benchmark uses two external libraries:
Special JS Feature/Syntax
There is no special JavaScript feature or syntax being used in this benchmark. All code snippets use standard ECMAScript 2020 syntax and features.
Other Alternatives
If you're interested in exploring alternative approaches, here are a few options:
Set
interface with spread
: Instead of converting Sets to arrays using Array.from()
, you can use the spread operator (...
) to merge two Sets into one. This approach is simpler and more efficient than converting both sets to arrays.Keep in mind that these alternatives may not provide the same level of immutability guarantees as using Immutable.js or the Set
interface with spread
.