<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 = 499; i >= 0; i--) {
arr2.push('' + i);
}
const finalArray1 = _.difference(arr1, arr2)
const finalArray2 = _.difference(arr2, arr1)
const outList2 = new Set([arr2]);
const outList1 = new Set([arr1]);
const finalArray1 = arr1.filter(value => !outList2.has(value));
const finalArray2 = arr2.filter(value => !outList1.has(value));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_difference | |
Set/Filter |
Test name | Executions per second |
---|---|
_difference | 1505.1 Ops/sec |
Set/Filter | 1762.5 Ops/sec |
I'll break down the benchmark and its results, explaining what's being tested, the different approaches, their pros and cons, and other considerations.
Benchmark Definition
The benchmark tests two ways to find the difference between two arrays: using Lodash's _difference
function and using JavaScript's built-in Set
data structure with filtering.
Script Preparation Code
The script generates two large arrays:
arr1
: an array of 10,000 elements from 0 to 9,999 (inclusive).arr2
: an array of 5,000 elements from 500 to -499 (inclusive).These arrays are used as input for the benchmark.
Html Preparation Code
The HTML code includes a script tag that loads the Lodash library version 4.17.5.
Individual Test Cases
There are two test cases:
This test case uses Lodash's _difference
function to find the difference between arr1
and arr2
. The resulting arrays are stored in finalArray1
and finalArray2
.
This test case uses JavaScript's built-in Set
data structure to find the difference between arr1
and arr2
. It creates two sets from the input arrays, then filters out elements that exist in both sets using the filter()
method. The resulting filtered arrays are stored in finalArray1
and finalArray2
.
Pros and Cons of each approach
_difference
function:Library: Lodash
Lodash is a popular utility library for JavaScript that provides a wide range of functions for tasks like string manipulation, array manipulation, and more. The _difference
function is part of Lodash's collection of array utilities.
Special JS feature or syntax: None
There are no special JavaScript features or syntax used in this benchmark.
Other considerations
_difference
function may make it more appealing for quick development, but it may also hide underlying complexities.Alternatives
Other alternatives for finding array differences include:
Array.prototype.filter()
and Array.prototype.find()
Note that the choice of approach depends on the specific requirements of the project, such as performance, readability, and maintainability.