<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var first = [Array(10000)].map(it => ~~(Math.random() * 1000));
var second = [Array(2220)].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 Array intersection |
Test name | Executions per second |
---|---|
Javascript Set intersection | 3125.2 Ops/sec |
Lodash intersection | 2180.9 Ops/sec |
Javascript Array intersection | 651.7 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark measures the performance of three approaches to find the intersection between two arrays or sets in JavaScript:
Set
data structureintersection
functionincludes
Options Compared
Set
data structure to create a set from each input array, and then filters out elements that are not present in the other set using the has
method.intersection
function to find the intersection between two arrays. The function takes two arguments, an array and another array, and returns a new array with only the elements that are common to both input arrays.includes
method to find the intersection between two arrays.Pros and Cons
Set
data structure, which might not be available in all environments (e.g., older browsers).Set
intersection due to the overhead of filtering.Library: Lodash
Lodash is a popular JavaScript library that provides a set of utility functions for various tasks, including array manipulation. The intersection
function is used to find the common elements between two arrays.
Special JS Feature/Syntax
There are no special JavaScript features or syntax used in this benchmark. All approaches use standard JavaScript methods and data structures.
Other Alternatives
Set
or Lodash.fast-set
which provides a faster implementation of sets compared to JavaScript's built-in Set
.