<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 Array intersection |
Test name | Executions per second |
---|---|
Javascript Set intersection | 478280.0 Ops/sec |
Lodash intersection | 497852.4 Ops/sec |
Javascript Array intersection | 863921.0 Ops/sec |
Let's dive into the benchmark.
The test is designed to measure the performance of three different approaches for finding intersections between two arrays or sets:
intersection
function from Lodash is used to calculate the intersection between two arrays.filter()
and includes()
to find the common elements between two arrays.Now, let's discuss the pros and cons of each approach:
Set Intersection
Pros:
Cons:
Lodash Intersection
Pros:
Cons:
Array Intersection
Pros:
Cons:
Now, let's talk about the library used in this benchmark: Lodash. Lodash is a popular utility library that provides various helper functions for tasks like array manipulation, string processing, and more. The intersection
function from Lodash is specifically designed to calculate the intersection between two arrays.
As for special JS features or syntax, there are none mentioned explicitly in the provided code snippets. However, it's worth noting that the use of arrow functions (=>
) and template literals (\r\n
) is a common pattern in modern JavaScript.
To achieve similar results, you can try using alternative libraries like lodash
(of course!), but also consider implementing the array intersection approach using standard JavaScript methods or exploring other alternatives like:
Array.prototype.reduce()
to find intersectionsfast-integer-set
for optimized set operationsKeep in mind that performance differences between these approaches may be subtle, and the choice ultimately depends on your specific use case, performance requirements, and personal preferences.