<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var arr1 = [];
for(let i = 0; i < 1000; i++) {
arr1.push('' + i);
}
var arr2 = [];
for(let i = 499; 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 | 36190.6 Ops/sec |
Set/Filter | 49112.7 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares two approaches for finding the difference between two arrays:
_.difference()
functionLodash _.difference() Function
The first approach uses Lodash's _.difference()
function to find the elements present in arr2
but not in arr1
. This function returns a new array containing only the unique elements from arr2
.
Pros:
Cons:
Set data structure with Array.prototype.filter()
The second approach uses a Set data structure in conjunction with Array.prototype.filter() to find the elements present in arr2
but not in arr1
. Here's how it works:
arr1
containing only its unique elements.arr2
to create a new array containing only the elements that are not present in the Set.Pros:
Cons:
Other Considerations
Both approaches have their trade-offs in terms of performance, readability, and maintainability. The choice between them depends on the specific use case and personal preference.
In general, if you need a fast and efficient solution with minimal overhead, using a Set data structure with Array.prototype.filter() might be the better choice. However, if you prioritize ease of use and don't mind loading an additional library, Lodash's _.difference()
function is a reliable and well-maintained option.
Library: Lodash
Lodash (formerly known as Underscore.js) is a popular JavaScript utility library that provides a wide range of functional programming helpers. The _.difference()
function is one of these helpers, designed to efficiently find the elements present in two arrays while excluding duplicates.
In this benchmark, we use the lodash.min.js
file from the CDN, which is a pre-compiled version of Lodash's source code optimized for production use. This allows us to easily load and use Lodash's functionality without modifying our own code.
Special JS Feature: Arrow Functions
The benchmark uses arrow functions (() => { ... }
) in both test cases, which are a modern JavaScript feature introduced in ECMAScript 2015 (ES6). Arrow functions provide a concise way to define small, single-expression functions without the need for function
declarations.
In this case, using arrow functions simplifies the code and makes it more readable. They're a common pattern in modern JavaScript development, especially when working with functional programming techniques.