<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.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 | 0.0 Ops/sec |
Lodash intersection | 317247.6 Ops/sec |
Javascript Array intersection | 103712.8 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares three approaches to find the intersection between two arrays or sets:
filter
method on an array._intersection
function from the Lodash library.Options Compared
The benchmark compares these three approaches for finding the intersection between two arrays or sets, with varying sizes (100 vs 20 elements). The options are compared in terms of performance (executions per second).
Pros and Cons of Each Approach
Lodash Library
The benchmark uses Lodash version 4.17.5. Lodash is a popular JavaScript utility library that provides a set of functional programming helpers. The _intersection
function takes two arrays as input and returns an array containing only the elements present in both arrays.
Special JS Features/Syntax
None mentioned in this benchmark, but it's worth noting that some modern JavaScript features like const
and arrow functions are not explicitly mentioned either.
Other Alternatives
If you need a faster Set intersection implementation, you could consider using a library like Fast-Set or SetInterval. If you prefer to implement the Set intersection from scratch, you can use the Map
data structure instead of Sets.
In summary, this benchmark provides a clear comparison between three approaches for finding intersections between arrays and sets, highlighting the trade-offs between ease of implementation, performance, and dependencies required.