<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
var testArr = [];
for (var i = 0; i < 100000; i++) {
testArr.push(String(getRandomInt(1000)));
}
const { resultArray } = testArr.reduce((result, item) => {
if(!result.resultMap[item]){
result.resultMap[item] = true;
result.resultArray.push(item)
}
return result;
}, {resultArray: [], resultMap: {}});
return resultArray;
const resultArray = [];
const resultMap = {};
for(let item of testArr) {
if(!resultMap[item]){
resultMap[item] = true;
resultArray.push(item)
}
}
return resultArray;
[new Set(testArr)]
_.uniq(testArr)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array Unique | |
For Loop | |
Array from Set | |
Lodash Uniq |
Test name | Executions per second |
---|---|
Array Unique | 246.6 Ops/sec |
For Loop | 262.9 Ops/sec |
Array from Set | 196.9 Ops/sec |
Lodash Uniq | 169.6 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Overview
The benchmark measures the performance of four different approaches to remove duplicates from an array of strings:
Set
data structure and the spread operator (new Set
) to create a set of unique elements, which is then converted back into an array.uniq()
function to remove duplicates from the array.for
loop, checking each element against an empty object ({}
) to determine if it exists in the result set.reduce()
method on the array, accumulating unique elements in an object (resultMap
) and pushing them onto a separate array (resultArray
).Options Compared
The benchmark compares these four approaches to see which one performs best:
Set
data structure and spread operator.for
loop.reduce()
method to accumulate unique elements.Pros and Cons
Here are some pros and cons of each approach:
Pros:
Set
data structure.Cons:
new Set()
).Set
.Pros:
Cons:
Pros:
Cons:
Pros:
reduce()
method.Cons:
{resultArray: []}
).Library: Lodash
The _uniq()
function is part of the popular Lodash utility library, which provides a collection of functional programming helper functions. Lodash can be used to simplify code and improve performance in various JavaScript tasks.
Special JS Feature/Syntax
None mentioned in this specific benchmark. However, it's worth noting that some modern JavaScript features like const
declarations, let
and var
hoisting, and the spread operator (...
) are used throughout the benchmark.
Other Alternatives
If you're looking for alternatives to these approaches or want to explore other methods for removing duplicates from an array:
includes()
method to remove duplicates.Array.from()
.I hope this explanation helps you understand the JavaScript microbenchmark on MeasureThat.net!