Skip to content

Instantly share code, notes, and snippets.

@celsopalmeiraneto
Last active September 14, 2022 17:43
Show Gist options
  • Save celsopalmeiraneto/7e03c34f261c758f8efbf89e9f257b4b to your computer and use it in GitHub Desktop.
Save celsopalmeiraneto/7e03c34f261c758f8efbf89e9f257b4b to your computer and use it in GitHub Desktop.
const { PerformanceObserver, performance } = require("node:perf_hooks");
const calculateWeight = (item) => {
const random = Math.random();
return Math.trunc(random * 1000);
};
const groupItemsByWeightImmutable = (items) =>
items.reduce((acc, item) => {
const weight = calculateWeight(item);
const itemsList = [...(acc[weight] ?? []), item];
return {
...acc,
[weight]: itemsList,
};
}, {});
const groupItemsByWeightMutable = (items) =>
items.reduce((acc, item) => {
const weight = calculateWeight(item);
acc[weight] = acc[weight] ?? [];
acc[weight].push(item);
return acc;
}, {});
const main = () => {
const observer = new PerformanceObserver((items) => {
const measures = items
.getEntries()
.map((entry) => ({ name: entry.name, duration: entry.duration }));
console.table(measures);
});
observer.observe({ type: "measure" });
[groupItemsByWeightImmutable, groupItemsByWeightMutable].forEach(
(groupItems) => {
[1, 10, 100, 1_000, 10_000, 100_000, 1_000_000].forEach((length) => {
const items = Array.from(new Array(length), () => null);
const markName = `${groupItems.name}, ${length}`;
performance.mark(markName);
groupItems(items);
performance.measure(
`${markName} - Time to process ${length}`,
markName
);
});
}
);
};
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment