<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var arr1 = [];
for(let i = 0; i < 100; i++) {
arr1.push('' + i);
}
var arr2 = [];
for(let i = 49; i >= 0; i--) {
arr2.push('' + i);
}
const notInArr1 = _.difference(arr2, arr1)
const notInArr2 = _.difference(arr1, arr2)
const notInArr1 = arr2.filter(value => !arr1.some(v => v === value));
const notInArr2 = arr1.filter(value => !arr2.some(v => v === value));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash | |
Set & Filter |
Test name | Executions per second |
---|---|
Lodash | 7723.7 Ops/sec |
Set & Filter | 13989.5 Ops/sec |
This benchmark compares two methods for finding the difference between two arrays in JavaScript. The primary focus is on evaluating the performance of using the Lodash library versus native JavaScript approaches with array methods like filter
and some
.
Lodash Library:
const notInArr1 = _.difference(arr2, arr1);
const notInArr2 = _.difference(arr1, arr2);
_.difference
function, which takes two arrays as arguments and returns a new array containing elements from the first array that are not present in the second array. This is done for both directions (i.e., arr2
against arr1
and arr1
against arr2
).JavaScript's Native Array Methods:
const notInArr1 = arr2.filter(value => !arr1.some(v => v === value));
const notInArr2 = arr1.filter(value => !arr2.some(v => v === value));
filter
function in conjunction with some
. For each element in one array, it filters out elements that exist in the other array by checking with some
to see if they are present.Lodash:
_.difference
function is straightforward and concise, making code easier to read and maintain.Native JavaScript Methods:
some
within a loop could degrade performance compared to optimized library functions.Using Sets: An alternative approach could involve using Set
, which can provide an efficient way to check for the existence of items. For example, you could convert one array into a set and then filter the other array based on membership in that set:
const set1 = new Set(arr1);
const notInArr1 = arr2.filter(value => !set1.has(value));
This method may yield better performance for large datasets since checking for existence in a Set is generally faster than using some
.
Custom Implementation: Depending on specific needs or constraints, engineers could also implement their own logic tailored for particular use cases, potentially optimizing for specific data shapes or access patterns.
In summary, this benchmark provides valuable insights into the performance implications of using a library versus relying on native capabilities in JavaScript for array manipulation tasks, along with considerations relevant for making informed choices in software development.