function dec2hex (dec) {
return dec < 10
? '0' + String(dec)
: dec.toString(16)
}
function generateId (len) {
var arr = new Uint8Array((len || 40) / 2)
window.crypto.getRandomValues(arr)
return Array.from(arr, dec2hex).join('')
}
var a = []
var b = []
for( let i = 0; i < 1000; i++)
{
a[i] = generateId(16)
b[i] = generateId(16)
}
function diff(a, b) {
const as = new Set(a);
const bs = new Set(b);
return Array.from(new Set([as].filter(x => !bs.has(x))));
}
const difference = a.filter(x => !b.includes(x));
_.difference(a, b)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
with Sets | |
with filter-includes | |
lodash.difference |
Test name | Executions per second |
---|---|
with Sets | 528247168.0 Ops/sec |
with filter-includes | 145.4 Ops/sec |
lodash.difference | 7627.5 Ops/sec |
Overview of the Benchmark
The provided benchmark measures the performance of three different approaches for finding the difference between two arrays in JavaScript: using Set
, filter
with includes
, and Lodash's difference
function.
Approaches Compared
Set
data structure to store unique elements from each array, and then filters out elements that are present in both sets.filter
method with the includes
method to find elements that are not present in the second array.difference
function, which is designed specifically for finding differences between arrays.Pros and Cons of Each Approach
Set
.Set
for each array), which can lead to higher memory usage.filter
and includes
) that are widely available in JavaScript.Library Used
The diff
function in the benchmark definition uses a custom implementation that creates two separate sets from each array using Set
. The actual implementation is:
const as = new Set(a);
const bs = new Set(b);
return Array.from(new Set([...as].filter(x => !bs.has(x))));
This library is not a standard JavaScript library, but rather a custom implementation designed for this specific benchmark.
Special JS Feature/Syntax
None of the approaches used special JavaScript features or syntax. They all rely on basic JavaScript methods and data structures (arrays, Set
, filter
).
Alternatives
Other alternatives to find differences between two arrays in JavaScript include:
indexOf()
method: Find elements that are not present in the second array by checking if an element is not at index -1
using indexOf()
.Map
: Similar to using Set
, but maps can be useful for more complex data structures or when preserving order matters.Array.prototype.diff()
from the fast-json-stubs
library.It's worth noting that the performance difference between these approaches may not be significant in all cases, and the choice ultimately depends on the specific requirements and constraints of the project.