<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var arr1 = [];
for(let i = 0; i < 10000; i++) {
arr1.push('' + i);
}
var arr2 = [];
for(let i = 490; i >= 0; i--) {
arr2.push('' + i);
}
const notInArr1 = _.difference(arr2, arr1)
const notInArr1 = arr2.filter(value => !arr1.includes(value));
const notInArr2 = arr1.filter(value => !arr2.includes(value));
const notInArr2 = _.difference(arr1, arr2)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash : small base | |
Set & Filter: small base | |
Set & Filter: large base | |
Lodash: large base |
Test name | Executions per second |
---|---|
Lodash : small base | 2775.3 Ops/sec |
Set & Filter: small base | 3762.3 Ops/sec |
Set & Filter: large base | 251.6 Ops/sec |
Lodash: large base | 8461.9 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
The provided benchmark compares two approaches to find elements that are not in an array using Lodash and the native filter()
method with includes()
. We'll break down what's being tested, the pros and cons of each approach, and discuss other alternatives.
What is being tested?
Three individual test cases are compared:
difference()
function from Lodash to find elements that are not in arr2
.filter()
method with a callback function that checks if an element is not included in arr1
using includes()
.difference()
function to find elements that are not in arr2
, but this time, first converting both arrays to sets.filter()
method with a callback function that checks if an element is not included in arr1
using includes()
, and then converting both arrays to sets.Options compared
The benchmark compares two main approaches:
Each approach has its pros and cons:
includes()
method.Library: Lodash
Lodash is a popular JavaScript library that provides a set of high-level functions for working with arrays, objects, and more. The difference()
function used in this benchmark is part of Lodash's utility functions, which makes it easier to perform array operations without having to write custom code.
Special JS feature: None
There are no special JavaScript features or syntax used in these benchmarks. They rely solely on standard JavaScript methods and Lodash functions.
Other alternatives
If you're interested in exploring alternative approaches, here are a few options:
Set.prototype.filter()
, Set.prototype.has()
) to achieve similar results without Lodash.Keep in mind that these alternatives may have different trade-offs in terms of readability, maintainability, and platform support.