<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var first = [Array(100)].map(it => ~~(Math.random() * 1000));
var second = [Array(20)].map(it => ~~(Math.random() * 1000));
const firstSet = new Set(first);
const secondSet = new Set(second);
new Set([firstSet].filter(item => secondSet.has(item)));
_.intersection(first, second)
first.filter(it => second.includes(it))
const setA = new Set(first);
const setB = new Set(second);
const _intersection = new Set()
for (const elem of setB) {
if (setA.has(elem)) {
_intersection.add(elem)
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Javascript Set intersection | |
Lodash intersection | |
Javascript Array intersection | |
set2 |
Test name | Executions per second |
---|---|
Javascript Set intersection | 201123.2 Ops/sec |
Lodash intersection | 390625.8 Ops/sec |
Javascript Array intersection | 110109.0 Ops/sec |
set2 | 270822.9 Ops/sec |
Let's dive into the provided benchmark.
Benchmark Overview
The benchmark compares four different approaches to find the intersection of two arrays: Lodash, Set (using JavaScript built-in Set
data structure), and two custom implementations using JavaScript arrays (filter()
and manual iteration).
Options Compared
intersection()
function from Lodash is used to find the intersection of two arrays.Set
data structure is used, which provides a fast way to perform set operations (union, intersection, difference).filter()
: The filter()
method is used on one of the arrays (first
) to create a new array containing only the elements that are also present in the other array (second
).Pros and Cons
filter()
:Library
The lodash
library is used as the third-party utility for performing set operations. Lodash provides a simple and efficient way to perform set intersections, unions, and differences.
Special JavaScript Features/Syntax
None of the benchmark test cases explicitly use special JavaScript features or syntax (e.g., async/await, ES6 classes). However, it's worth noting that some browsers may have implemented certain experimental features or optimizations that might affect the results.
Other Alternatives
If you're interested in exploring alternative approaches, here are a few options:
reduce()
: An alternative to filter()
, but with different performance characteristics.includes()
method on arrays: A simpler way to check if an element is present in an array, but may not be as efficient for large datasets.for...of
loop: Another approach to finding the intersection of two sets using a custom iteration loop.Keep in mind that each alternative has its own trade-offs and performance characteristics, which might affect the results of your benchmarking tests.