<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);
firstSet.intersection(secondSet)
_.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 | 442965.2 Ops/sec |
Lodash intersection | 601986.9 Ops/sec |
Javascript Array intersection | 602414.2 Ops/sec |
The benchmark compares three different methods for finding the intersection of two collections of numbers: one using JavaScript's native Set
object, another using the popular utility library Lodash, and the last one using a straightforward array method in JavaScript. The intersection operation here refers to identifying the common elements between two collections.
Javascript Set Intersection
const firstSet = new Set(first);
const secondSet = new Set(second);
firstSet.intersection(secondSet);
Set
object in JavaScript, which stores unique values. The intersection is formed by explicitly applying a method that would check and return the common elements.Set
.intersection
method must be implemented, as it does not exist natively on Set
, which adds some complexity.Lodash Intersection
_.intersection(first, second);
intersection
function to find common elements.Javascript Array Intersection
first.filter(it => second.includes(it));
filter()
method combined with includes()
to find common elements.includes
involves a linear search for each element in first
, resulting in O(n*m) complexity.The latest benchmark results demonstrate the effectiveness of each method in terms of executions per second:
From the results, we can see that both the JavaScript Array Intersection and Lodash Intersection perform similarly well, significantly outpacing the JavaScript Set Intersection in terms of execution speed.
Other alternatives to consider may include:
Array.reduce()
for Custom Intersection Logic: More flexibility for complex intersection scenarios might be achieved through higher-order functions.Each method's suitability will ultimately rely on specific application requirements, considering both performance and readability.