<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 secondSetSet = new Set(second);
new Set(first.filter(
item => secondSetSet.has(item)));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Javascript Set intersection | |
Lodash intersection | |
Javascript Array intersection | |
Js array Set intersection |
Test name | Executions per second |
---|---|
Javascript Set intersection | 80506.9 Ops/sec |
Lodash intersection | 144096.3 Ops/sec |
Javascript Array intersection | 26429.0 Ops/sec |
Js array Set intersection | 61769.9 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Benchmark Overview
The benchmark measures the performance of three different approaches to find the intersection between two arrays:
What are the options being compared?
The three options being compared are:
Set
data structure to store the elements of the first array, and then filters out the elements that are not present in the second array.intersection()
function from the Lodash library to find the intersection between two arrays.filter()
method to create a new array that contains only the elements that are common to both arrays.Pros and Cons of each approach
Here's a brief summary of the pros and cons of each approach:
Set
object, which can have additional overhead due to memory allocation and garbage collection.filter()
method.filter()
method iterates over the elements of one array for each element in the other array.Library used: Lodash
Lodash is a popular JavaScript utility library that provides a wide range of functions for tasks such as string manipulation, array and object manipulation, and more. In this benchmark, the intersection()
function from Lodash is used to find the intersection between two arrays.
Special JS feature or syntax: Sets (JavaScript)
Sets are a data structure in JavaScript that allows you to store unique values without duplicates. They're implemented as hash tables, which enables fast lookup and insertion operations. In this benchmark, sets are used to implement the JavaScript Set Intersection approach.
Overall, the choice of approach depends on the specific requirements of your use case. If performance is critical, JavaScript Set Intersection might be a good choice due to its efficient time complexity. However, if simplicity and ease of implementation are more important, JavaScript Array Intersection might be a better fit.