<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var arr1 = [];
for(let i = 0; i < 10000; i++) {
arr1.push('' + i);
}
var arr2 = [];
for(let i = 490; i >= 0; i--) {
arr2.push('' + i);
}
const notInArr1 = _.difference(arr2, arr1)
const notInArr2 = _.difference(arr1, arr2)
const arr1Set = new Set();
const arr2Set = new Set();
arr1.forEach(value => arr1Set.add(value));
arr2.forEach(value => arr2Set.add(value));
const notInArr1 = arr2.filter(value => !arr1Set.has(value));
const notInArr2 = arr1.filter(value => !arr2Set.has(value));
const arr1Set = new Set([arr1]);
const arr2Set = new Set([arr2]);
const notInArr1 = arr2.filter(value => !arr1Set.has(value));
const notInArr2 = arr1.filter(value => !arr2Set.has(value));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash | |
Set & Filter | |
Set & Filter (new set) |
Test name | Executions per second |
---|---|
Lodash | 2721.9 Ops/sec |
Set & Filter | 235.2 Ops/sec |
Set & Filter (new set) | 157.9 Ops/sec |
I'll break down the benchmark and its test cases to explain what's being tested, compared, and their pros and cons.
Benchmark Overview
The benchmark is designed to compare three approaches for finding elements in two large arrays:
_difference
method)Set
and filtering (filter
method)Set
and filtering with new sets (creating new sets from the original arrays)Test Cases
Each test case measures the execution time of one of these approaches.
The benchmark uses Lodash's _difference
method to find elements in arr2
that are not in arr1
. This method returns a new array containing only the unique elements from the first array and rejecting duplicates.
Pros:
Cons:
arr1
or arr2
are very large.This approach uses two separate Set
objects to store unique elements from both arrays and then filters out the common elements using the filter
method.
Pros:
Cons:
This approach creates new Set
objects from both arrays using array spread ([...arr]
) and then filters out common elements.
Pros:
Cons:
Library and Syntax Considerations
_difference
method.Set
objects are a built-in JavaScript data structure that allows you to store unique values.Device-Specific Considerations
The test results were obtained on a Chrome 108 browser running on a Mac with macOS 10.15.7. The device platform and operating system may affect the benchmark's performance, as some features or optimizations might be unavailable or less efficient on certain platforms.
Other Alternatives
If you need to compare other approaches for finding elements in two arrays, consider using:
Array.prototype.some()
and Array.prototype.find()
: These methods can be used to find common or unique elements between two arrays.Promise.all()
: This method can be used to compare the performance of multiple array operations in parallel.When choosing an approach, consider factors like memory usage, filter complexity, and potential overhead from set creation.