<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var arr1 = [];
for(let i = 0; i < 50000; i++) {
arr1.push('' + i);
}
var arr2 = [];
for(let i = 4990; i >= 0; i--) {
arr2.push('' + i);
}
const finalArray = _.difference(arr2, arr1)
const outList = new Set([arr1]);
const finalArray = arr2.filter(value => !outList.has(value));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_difference | |
Set/Filter |
Test name | Executions per second |
---|---|
_difference | 65.2 Ops/sec |
Set/Filter | 63.7 Ops/sec |
The provided JSON represents two JavaScript microbenchmarks for testing the performance of two different approaches to find the difference between two large arrays.
Benchmark 1: Lodash _difference
The benchmark measures the performance of Lodash's _difference
function, which takes two arrays as input and returns a new array containing only the elements that are present in the first array but not in the second. The two arrays, arr1
and arr2
, are populated with 50,000 and 49,990 integers, respectively.
Benchmark 2: ES6 Set + Filter
The benchmark measures the performance of a combination of an ES6 Set and the filter
method to find the difference between the same two arrays. The process works as follows:
arr1
) using the spread operator ([...arr1]
). This allows for efficient lookups.arr2
) by checking if each element is not present in the set created from arr1
using the has
method.Options compared
The two approaches being tested are:
_difference
functionPros and Cons
Lodash _difference
Pros:
Cons:
ES6 Set + Filter
Pros:
Cons:
Library
Lodash is a popular JavaScript utility library that provides many functional programming helpers, including _difference
. It can be included in a project by adding a script tag referencing its CDN or downloading and importing it locally.
Special JS feature/Syntax
There is no special JavaScript feature or syntax used in these benchmarks. Both approaches use standard JavaScript features like arrays, sets, loops, and filter methods.
Other alternatives
If you want to test alternative approaches for finding the difference between two large arrays, some other options could include:
Array.prototype.filter()
with a custom comparison function