Skip to content

Instantly share code, notes, and snippets.

@theScottyJam
Created February 18, 2023 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theScottyJam/8424183e49f4555b60752b21f1076129 to your computer and use it in GitHub Desktop.
Save theScottyJam/8424183e49f4555b60752b21f1076129 to your computer and use it in GitHub Desktop.
sorted uniq benchmarks
const _ = require('lodash');
// Alter these values to see how it affects the overall performance.
const NUMBER_OF_UNIQUE_ITEMS = 100;
const NUMBER_OF_DUPLICATES_PER_ITEM = 10000;
const TRIALS = 100;
function buildArray() {
const result = [];
for (let i = 0; i < NUMBER_OF_UNIQUE_ITEMS; ++i) {
for (let j = 0; j < NUMBER_OF_DUPLICATES_PER_ITEM; ++j) {
result.push(i);
}
}
return result;
}
function lodashUniq(array) {
return _.sortedUniq(array);
}
function unoptimized(array) {
return [...new Set(array)];
}
function vanillaUniq(array) {
if (array.length === 0) {
return [];
}
const result = [array[0]];
for (const value of array) {
if (result[result.length - 1] !== value) {
result.push(value);
}
}
return result;
}
function run(...fns) {
const totals = fns.map(() => 0);
for (let i = 0; i < TRIALS; ++i) {
for (const [i, fn] of Object.entries(fns)) {
const array = buildArray();
const start = performance.now();
fn(array);
const end = performance.now();
totals[i] += end - start;
}
}
for (const [i, total] of Object.entries(totals)) {
console.log(`${fns[i].name}: ${total}`);
}
}
run(lodashUniq, vanillaUniq, unoptimized);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment