<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
var itemsA = [];
var itemsB = [];
for (let i = 0; i < 1000; i++) {
itemsA.push(getRandomInt(500));
itemsB.push(getRandomInt(500));
}
itemsA.sort(function(a,b){ return a-b; });
itemsB.sort(function(a,b){ return a-b; });
function* sortedDifference(sortedIterableA, sortedIterableB) {
let iteratorA = sortedIterableA[Symbol.iterator]();
let iteratorB = sortedIterableB[Symbol.iterator]();
let itemA = iteratorA.next();
let itemB = iteratorB.next();
while (!itemA.done) {
if (itemB.done) {
yield itemA.value;
yield* iteratorA;
return;
}
if (itemA.value < itemB.value) {
yield itemA.value;
itemA = iteratorA.next();
} else {
if (! (itemB.value < itemA.value)) {
itemA = iteratorA.next();
}
itemB = iteratorB.next();
}
}
}
function difference(setA, setB) {
let _difference = new Set(setA)
for (let elem of setB) {
_difference.delete(elem)
}
return Array.from(_difference).sort();
}
let itemsC = Array.from(sortedDifference(itemsA, itemsB));
let itemsC = difference(itemsA, itemsB);
let itemsC = _.difference(itemsA, itemsB);
let itemsC = R.difference(itemsA, itemsB);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Port from C++ STL | |
Difference algorithm from MDN Set page | |
Lodash _.difference | |
Ramda R.difference |
Test name | Executions per second |
---|---|
Port from C++ STL | 26032.7 Ops/sec |
Difference algorithm from MDN Set page | 5871.6 Ops/sec |
Lodash _.difference | 18179.0 Ops/sec |
Ramda R.difference | 3092.5 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Definition
The benchmark is designed to compare three different approaches for finding the difference between two sorted arrays:
sortedDifference
function, which is a custom implementation of the algorithm used in the C++ Standard Template Library (STL).difference
function provided by the Mozilla Developer Network (MDN) documentation for finding the difference between two sets._difference
function from the Lodash library, which is a popular utility library for JavaScript.R.difference
function from the Ramda library, which is another popular functional programming library.Options Compared
The benchmark compares the performance of these four approaches on two sorted arrays (itemsA
and itemsB
) generated randomly. The test measures the number of executions per second for each approach.
Pros and Cons of Each Approach
Other Considerations
Set
data structure in the MDN implementation and Lodash library may introduce performance overhead compared to a custom implementation using iterators.Library and Syntax
_difference
is one of its functions.Alternatives
Other alternatives to consider when finding the difference between two sorted arrays include: