<script src='https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js'></script>
/*your preparation JavaScript code goes here
To execute async code during the script preparation, wrap it as function globalMeasureThatScriptPrepareFunction, example:*/
async function globalMeasureThatScriptPrepareFunction() {
// This function is optional, feel free to remove it.
// await someThing();
}
var options = [];
for (var i = 0; i < 250000; i++) {
options.push(i)
}
var l = new Set([options]);
return l;
var options = [];
for (var i = 0; i < 250000; i++) {
options.push(i)
}
return _.uniq(options);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
set | |
lodash |
Test name | Executions per second |
---|---|
set | 1887.4 Ops/sec |
lodash | 99.5 Ops/sec |
The benchmark titled "set vs uniq" is aimed at comparing the performance of two different approaches to obtaining unique values from an array of numbers: using the built-in JavaScript Set
object and using the _.uniq
function from the Lodash library.
Using JavaScript Set
:
var options = [];
for (var i = 0; i < 250000; i++) {
options.push(i);
}
var l = new Set([options]);
return l;
options
containing integers from 0 to 249,999. It then creates a Set
object using this array. Set
data structure automatically filters out duplicate values, providing a collection of unique items.Using Lodash's _.uniq
:
var options = [];
for (var i = 0; i < 250000; i++) {
options.push(i);
}
return _.uniq(options);
options
array but uses the _.uniq
function from Lodash to extract unique values from the array. uniq
method scans through the entire array and constructs a new array containing only the unique values.JavaScript Set
:
Array.from(set)
or using spread syntax).Lodash _.uniq
:
Set
for very large arrays since it must traverse and create a new array.Set
approach (approximately 405.59 executions per second) is significantly faster than using _.uniq
(approximately 45.50 executions per second).Set
object is part of ES6 (ECMAScript 2015) and is widely supported in modern browsers. However, developers must ensure compatibility in older environments.Set
is preferable._.uniq
could fit seamlessly into the codebase.Array.prototype.filter
or the use of Array.prototype.reduce
can also achieve unique values without external libraries. However, these approaches may be less efficient:var unique = options.filter((value, index, self) => self.indexOf(value) === index);
Map
to track occurrences can be a flexible option, although potentially more verbose.Choosing between these methods depends on the specific use case, performance requirements, and the existing stack of libraries in use.