<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 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));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash | |
Set & Filter |
Test name | Executions per second |
---|---|
Lodash | 72339.9 Ops/sec |
Set & Filter | 182242.2 Ops/sec |
Overview of the Benchmark
The provided JSON represents a JavaScript microbenchmark test case, where two approaches are compared: using Lodash's difference
method and using Sets with filtering.
Benchmark Definition
The benchmark definition consists of two scripts:
arr1
and arr2
, containing 100 and 51 elements respectively, in ascending order.Individual Test Cases
There are two test cases:
The benchmark definition for this test case is:
const notInArr1 = _.difference(arr2, arr1)
const notInArr2 = _.difference(arr1, arr2)
This code uses the _.difference
method from Lodash to find the elements that are in arr2
but not in arr1
, and vice versa.
Pros and Cons
The benchmark definition for this test case is:
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))
This code creates two Sets, arr1Set
and arr2Set
, from the arrays arr1
and arr2
. It then uses the filter
method to find the elements that are in one set but not the other.
Pros and Cons
Library: Lodash
Lodash is a popular JavaScript utility library that provides various functions for tasks such as array manipulation, object manipulation, and string manipulation. The difference
method is part of the Lodash library's set operations capabilities.
Special JS Feature or Syntax
None mentioned in this benchmark.
Other Alternatives
Other alternatives to compare these two approaches could include:
Set
and filter
, without relying on a library like Lodash.Array.prototype.findIndex()
or Array.prototype.indexOf()
, for set operations.Keep in mind that the choice of approach depends on the specific use case and performance requirements.