const input = new Array(300).fill(0).flatMap((_, i) => {
const keyBase = i * 4;
i *= 400;
return [
{ key: (keyBase).toString(36), start: i + 0, end: i + 100 }, // 100ms of duration
{ key: (keyBase + 1).toString(36), start: i + 10, end: i + 30 }, // 20ms of duration
{ key: (keyBase + 2).toString(36), start: i + 110, end: i + 200 }, // 90ms of duration
{ key: (keyBase + 3).toString(36), start: i + 300, end: i + 400 },
];
});
const method1 = () => input.reduce(
(outArray, { key, start, end }, idx) => {
const nextStart = Math.max(start, outArray[idx - 1]?.end ?? 0);
outArray.push({
key,
start: nextStart,
end: nextStart + end - start,
});
return outArray;
},
[]
);
const method2 = () => input.reduce(
(outArray, { key, start, end }, idx) => [
...outArray,
{
key,
start: Math.max(start, outArray[idx - 1]?.end ?? 0),
end: Math.max(start, outArray[idx - 1]?.end ?? 0) + end - start
}
],
[]
);
const sum = (acc, x) => acc + x;
const avg = arr => arr.reduce(sum, 0) / arr.length;
const methods = ['Method1', 'Method2'];
const obs = new PerformanceObserver(items =>
['Method1', 'Method2'].forEach(m =>
console.log(m, avg(items.getEntriesByName(m).map(e => e.duration)))
));
obs.observe({ type: 'measure', buffered: true });
for (let i = 0; i < 20000; i++) {
methods.forEach((m, i) => {
performance.mark(i);
i === 0 ? method1() : method2();
i === 0 ? performance.measure(m, i) : performance.measure(m, 0, i);
});
}
setTimeout(() => obs.disconnect(), 0);