<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var arr1 = [];
for(let i = 0; i < 100000; i++) {
arr1.push(i.toString());
}
var arr2 = [];
for(let i = 9999; i >= 0; i--) {
arr2.push(i.toString());
}
const notInArr2 = _.difference(arr1, arr2)
const arr2Set = new Set(arr2);
const notInArr2 = arr1.filter(value => !arr2Set.has(value));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash | |
Set & Filter |
Test name | Executions per second |
---|---|
Lodash | 243.8 Ops/sec |
Set & Filter | 280.0 Ops/sec |
Let's break down the provided JSON and explain what is tested, compared, and some pros and cons of different approaches.
Benchmark Context
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks. The benchmark in question compares two approaches for finding elements not present in an array arr2
within another array arr1
. One approach uses the Lodash library, while the other uses a set-based approach.
Script Preparation Code
The script preparation code generates two arrays:
arr1
: An array of 100,000 string elements created by pushing incrementing integers (from 0 to 99999) as strings.arr2
: An array of 10,000 decrementing integer elements (from 9999 to 0), also as strings.Html Preparation Code
The HTML preparation code includes a reference to the Lodash JavaScript library version 4.17.5.
Benchmark Definition JSON
The benchmark definition consists of two test cases:
_.difference
function from Lodash to find elements not present in arr2
.arr2
, and then uses the filter
method with a callback function to exclude elements that are present in the set.Comparison
The comparison between these two approaches is aimed at measuring their performance. The test cases aim to determine which approach is faster, more efficient, or has better performance characteristics under various conditions.
Pros and Cons of Different Approaches
_.difference
):Library Used - Lodash
Lodash is a popular JavaScript utility library that provides a wide range of functions for data manipulation, array operations, string manipulation, and more. The _.difference
function is part of this library and returns an array containing all elements present in the first argument but not in the subsequent arguments.
Special JS Feature or Syntax - Set
The use of Sets in this benchmark takes advantage of JavaScript's built-in Set data structure, which provides efficient membership testing and iteration. This allows for faster lookup and exclusion of elements from arr1
when comparing with arr2
.
Alternatives
Other approaches could be explored, such as:
Array.prototype.forEach
and conditional statements to iterate through arr1
and compare elements with arr2
.Keep in mind that the performance of these alternative approaches might vary depending on specific requirements, system configurations, and the size of input datasets.