<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 finalArray = _.difference(arr1, arr2)
const set2 = new Set([arr2]);
const finalArray = arr1.filter(value => !set2.has(value));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_difference | |
Set/Filter |
Test name | Executions per second |
---|---|
_difference | 85846.0 Ops/sec |
Set/Filter | 188622.7 Ops/sec |
Let's break down the provided benchmark and its test cases.
Benchmark Overview
MeasureThat.net is a website where users can create and run JavaScript microbenchmarks to compare different approaches for achieving a specific goal. The benchmark in question is comparing two methods: using the difference
function from the Lodash library, and using a Set to filter out elements from an array.
Script Preparation Code
The script preparation code generates two arrays: arr1
and arr2
. arr1
contains 100 elements starting from 0 and incrementing by 1 (using var arr1 = []; for(let i = 0; i < 100; i++) { ... }
). arr2
contains the same number of elements, but in reverse order, starting from 99 and decrementing by 1 (using for(let i = 49; i >= 0; i--) { ... }
).
Html Preparation Code
The HTML preparation code includes a reference to Lodash version 4.17.5, which is used as the library for the _difference
test case.
Test Cases
There are two individual test cases:
difference
function from Lodash to find the elements that exist in arr1
but not in arr2
. The benchmark code is: const finalArray = _.difference(arr1, arr2)
.arr1
that are present in arr2
. The benchmark code is: const set2 = new Set([...arr2]); const finalArray = arr1.filter(value => !set2.has(value))
.Comparison of Approaches
The two approaches differ in their performance characteristics:
difference
function is optimized for performance and has a relatively low overhead.arr2
, and then filters out elements from arr1
using the has
method of the Set. This approach requires creating a new Set, which can be slower than using a library function.Pros and Cons
has
method calls.Other Considerations
_difference
approach is likely to remain faster due to its optimized library function._difference
approach uses less memory since it only stores a reference to the Lodash function and the two input arrays. The Set/Filter
approach requires creating a new Set, which can increase memory usage.Alternative Approaches
Other approaches that could be used instead of the _difference
and Set/Filter
methods include:
It's worth noting that the choice of approach ultimately depends on the specific requirements and constraints of the project. The MeasureThat.net benchmark provides a useful comparison between two popular approaches, but other considerations may need to be taken into account when selecting an optimal solution.