<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
var arr = [];
var arr2 = [];
for(var i = 0; i < 51; i++){
arr.push(getRandomInt(100));
arr2.push(getRandomInt(100));
}
_.intersection(arr,arr2);
var getArrayIntersection = (a, b) => {
var setA = new Set(a),
setB = new Set(b);
var comparator = {
array: setA,
set: setB,
};
if (setA.size > setB.size) {
comparator.array = setB;
comparator.set = setA;
}
const intersection = [comparator.array].filter((el) =>
comparator.set.has(el),
);
return intersection;
};
getArrayIntersection(arr, arr2);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash | |
sort |
Test name | Executions per second |
---|---|
lodash | 400602.2 Ops/sec |
sort | 434852.7 Ops/sec |
Let's break down what is being tested in this benchmark.
Benchmark Purpose
The purpose of this benchmark is to compare the performance of two approaches for finding the intersection of two arrays: using Lodash's intersection
function and implementing a custom solution.
Options Compared
intersection
function: This approach uses the built-in intersection
function from the Lodash library, which takes two arrays as input and returns an array containing only the elements that are common to both arrays.Pros and Cons
intersection
function:Library used The benchmark uses the Lodash library version 4.17.5.
Special JavaScript feature/syntax There are no special JavaScript features or syntax used in this benchmark.
Other considerations
Alternative approaches
Array.prototype.filter()
can be used as alternatives.Array.prototype.filter()
with a callback function.Overall, this benchmark provides a useful comparison between two approaches to finding the intersection of arrays, highlighting the trade-offs between using an existing library versus implementing a custom solution.