Performance API
Performance API
Section titled “Performance API”Introduction
Section titled “Introduction”The Performance API provides tools to measure the performance of your JavaScript code with high-resolution timestamps.
Topics Covered
Section titled “Topics Covered”- performance.now() — High-resolution timing with sub-millisecond precision
- Marks & Measures — Using performance.mark() and performance.measure()
- Performance Observer — Monitoring long tasks and other metrics
performance.now()
Section titled “performance.now()”const start = performance.now();
// Code to measurefor (let i = 0; i < 1000000; i++) { Math.sqrt(i);}
const end = performance.now();console.log(`Took ${end - start}ms`);Performance Marks & Measures
Section titled “Performance Marks & Measures”// Mark specific points in timeperformance.mark('start');// ... do work ...performance.mark('end');
// Measure between marksperformance.measure('myOperation', 'start', 'end');
// Get the measurementconst measures = performance.getEntriesByType('measure');console.log(measures[0].duration);
// Clean upperformance.clearMarks();performance.clearMeasures();User Timing
Section titled “User Timing”performance.mark('fetch-start');
await fetch('/api/data');
performance.mark('fetch-end');performance.measure('data-fetch', 'fetch-start', 'fetch-end');
const measure = performance.getEntriesByName('data-fetch')[0];console.log(`Fetch took ${measure.duration}ms`);Performance Observer
Section titled “Performance Observer”// Monitor long tasks (tasks > 50ms)const observer = new PerformanceObserver((list) => { list.getEntries().forEach((entry) => { console.log(`Long task detected: ${entry.duration}ms`); });});
observer.observe({ entryTypes: ['longtask'] });Summary
Section titled “Summary”performance.now()— high-resolution timingperformance.mark()/.measure()— custom measurementsPerformanceObserver— monitor specific metrics- Critical for finding and fixing performance bottlenecks