<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))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Javascript Set intersection | |
Lodash intersection | |
Javascript intersection |
Test name | Executions per second |
---|---|
Javascript Set intersection | 194850.8 Ops/sec |
Lodash intersection | 277950.4 Ops/sec |
Javascript intersection | 95951.9 Ops/sec |
Let's break down the provided JSON and benchmarking results to understand what's being tested.
Benchmark Overview
The test compares three approaches for finding the intersection of two arrays:
Set
objects in JavaScript, which are implemented as hash tables for efficient lookups.intersection
function from the Lodash library, a popular utility belt for functional programming tasks..filter()
method to find common elements between two arrays.Options Compared
The test compares the performance of these three approaches:
Set
objects from the input arrays and then uses another Set
constructor with a filter method to compute the intersection.intersection
function from Lodash, which takes two arrays as arguments and returns their intersection.Set
, and then filters it against the other array.Pros and Cons
Here's a brief analysis of each approach:
Set
objects, which might incur overhead for small arrays.Set
objects under the hood).Set
, which can be slower for small inputs.Library: Lodash
Lodash is a popular JavaScript library that provides a collection of functional programming utilities. The intersection
function is part of this utility belt and allows you to compute the intersection of two arrays efficiently.
Special JS Feature/Syntax
None mentioned explicitly in the provided benchmark code, but it's worth noting that some modern JavaScript features like Symbol or BigInt might be used for more advanced benchmarking scenarios. However, these are not present in this specific example.
Other Alternatives
For finding array intersections, you can also consider other libraries or implementations, such as:
intersection
function.Keep in mind that the choice of implementation often depends on specific requirements, such as performance, memory usage, or code simplicity.