<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var arr1 = [];
var arr2 = [];
var arr3 = [];
var arr4 = [];
for (i = 0; i < 1000; i++) {
arr1.push(getRandom());
arr2.push(getRandom());
arr3.push(getRandom());
arr4.push(getRandom());
arr1.sort();
arr2.sort();
arr3.sort();
arr4.sort();
}
function getRandom() {
const minimum = 1;
const maximum = 1000;
var randomnumber = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
return randomnumber;
}
const results = new Set(_.intersection(arr1, arr2, arr3, arr4));
function intersectMultipleArrays(arrays) {
if (arrays.length === 0) return new Set();
// Sort arrays by length to optimize operations
arrays.sort((a, b) => a.length - b.length);
// Start with the smallest array as the base intersection set
let intersection = new Set(arrays[0]);
// Iterate over the remaining arrays and filter the intersection
for (let i = 1; i < arrays.length; i++) {
intersection = new Set(arrays[i].filter(item => intersection.has(item)));
// Early exit if intersection is empty
if (intersection.size === 0) return new Set();
}
// Return the final Set
return intersection;
}
const results = intersectMultipleArrays(arr1, arr2, arr3, arr4);
const results = new Set(
[arr1, arr2, arr3, arr4]
.sort((a, b) => b.length - a.length)
.reduce((a, b) => a.filter(aValue => b.includes(aValue)))
);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash _.intersection() | |
Custom optimized function 1 (Best) | |
Custom optimized function 2 |
Test name | Executions per second |
---|---|
Lodash _.intersection() | 5088.8 Ops/sec |
Custom optimized function 1 (Best) | 6959.0 Ops/sec |
Custom optimized function 2 | 3813.1 Ops/sec |
Measuring performance differences between various JavaScript approaches to solve the same problem is crucial for optimization and development efficiency.
Benchmark Overview
The provided benchmark compares three different methods to find the intersection of multiple sorted arrays:
reduce()
method to filter the intersection.Options Compared
The three methods are compared in terms of their execution speed.
Pros and Cons of Each Approach
reduce()
method.reduce()
.Library Usage
Lodash is a popular utility library that provides a wide range of functions for common tasks, including array manipulation. In this benchmark, Lodash _.intersection() is used as-is from the library.
Special JS Features or Syntax
None mentioned in the provided benchmark.
Other Considerations
Alternative Approaches
Other possible approaches to find the intersection of multiple sorted arrays include:
Array.prototype.filter()
and manual iteration.While these alternative approaches might be viable, they are not directly compared in this benchmark.