<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 notInArr = _.difference(arr2, arr1)
const arr2Set = new Set();
arr2.forEach(value => arr2Set.add(value));
const notInArr2 = arr1.filter(value => !arr2Set.has(value));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash | |
Set & Filter |
Test name | Executions per second |
---|---|
Lodash | 42817.4 Ops/sec |
Set & Filter | 342209.5 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Benchmark Overview
The benchmark measures the performance difference between using Lodash's difference
function and creating an array with Set data structure followed by filtering (using filter()
method) for finding elements not present in the first array (arr1
) versus a second array (arr2
). The arrays arr1
and arr2
are populated with ascending numbers.
Options Compared
Two approaches are compared:
difference
function to find elements that are in arr1
but not in arr2
.arr2
and using the filter()
method to find elements present in arr1
.Pros and Cons of Each Approach
Pros:
Cons:
Pros:
Cons:
arr2
and then filtering arr1
.Library Used: Lodash
Lodash is a popular utility library for JavaScript that provides a collection of functions and methods for various tasks, including array manipulation. In this benchmark, Lodash's difference
function is used to find elements present in arr1
but not in arr2
.
Special JS Feature/Syntax: None
There are no special JavaScript features or syntax used in the benchmark.
Other Alternatives
If you're looking for alternative approaches, here are a few:
indexOf()
method on each element of one array to check if an element exists in another array.forEach()
and includes()
(if supported) for filtering.Keep in mind that performance can vary depending on specific use cases, browser versions, and system configurations. The choice of approach ultimately depends on your project requirements, performance constraints, and personal preference.