Measure how long code takes

performance.now() and marks give precise timings. Log them, then fix what is really slow.

JavaScript · Measure how long code takesAdvanced
function timeIt(label, fn) {
  performance.mark(label + ':start');
  const result = fn();
  performance.mark(label + ':end');
  performance.measure(label, label + ':start', label + ':end');
  const ms = performance.getEntriesByName(label).at(-1).duration;
  console.log(`${label}: ${ms.toFixed(1)} ms`);
  return result;
}

timeIt('sort', () => Array.from({ length: 100000 }, (_, i) => (i * 7919) % 10007).sort((a, b) => a - b));

new PerformanceObserver((list) => list.getEntries().forEach((e) => console.log('LCP', e.startTime)))
  .observe({ type: 'largest-contentful-paint', buffered: true });
performancemeasuremarktiming