InterviewHubPRO
Section Overview
Q516

Question 516 of 521

Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 521)

99%
JavaScript Internals (521 Qs)•Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 521)

What is the Performance API and how is it used for measuring performance?

The Performance API provides high-precision timing information for measuring web application performance.

Basic timing:

javascript
 // High-resolution timestamp
 const start = performance.now();

 // Some operation
 for (let i = 0; i < 1000000; i++) {}

 const end = performance.now();
 console.log(`Operation took ${end - start} milliseconds`);

Navigation timing:

javascript
 // Get page load metrics
 const perfData = performance.getEntriesByType('navigation')[0];

 console.log('DNS lookup:', perfData.domainLookupEnd - perfData.domainLookupStart);
 console.log('TCP connection:', perfData.connectEnd - perfData.connectStart);
 console.log('Request time:', perfData.responseStart - perfData.requestStart);
 console.log('Response time:', perfData.responseEnd - perfData.responseStart);
 console.log('DOM processing:', perfData.domContentLoadedEventEnd - perfData.domContentLoadedEventStart);
 console.log('Total load time:', perfData.loadEventEnd - perfData.fetchStart);

Custom performance marks and measures:

javascript
 // Mark the start of an operation
 performance.mark('operation-start');

 // Do some work
 await fetchData();
 processData();

 // Mark the end
 performance.mark('operation-end');

 // Measure the duration
 performance.measure('operation', 'operation-start', 'operation-end');

 // Get the measurement
 const measures = performance.getEntriesByName('operation');
 console.log(`Operation took ${measures[0].duration}ms`);

 // Clean up
 performance.clearMarks();
 performance.clearMeasures();

Resource timing:

javascript
 // Get all resource timings
 const resources = performance.getEntriesByType('resource');

 resources.forEach(resource => {
   console.log(`${resource.name}:`);
   console.log(`  Duration: ${resource.duration}ms`);
   console.log(`  Size: ${resource.transferSize} bytes`);
   console.log(`  Type: ${resource.initiatorType}`);
 });

 // Filter specific resources
 const images = performance.getEntriesByType('resource')
   .filter(r => r.initiatorType === 'img');

Function execution time:

javascript
 function measureFunction(fn, ...args) {
   const start = performance.now();
   const result = fn(...args);
   const end = performance.now();

   console.log(`${fn.name} took ${end - start}ms`);
   return result;
 }

 async function measureAsync(fn, ...args) {
   const start = performance.now();
   const result = await fn(...args);
   const end = performance.now();

   console.log(`${fn.name} took ${end - start}ms`);
   return result;
 }

 measureFunction(expensiveOperation, arg1, arg2);
 await measureAsync(asyncOperation, arg1);

Performance Observer (monitoring):

javascript
 const observer = new PerformanceObserver((list) => {
   list.getEntries().forEach(entry => {
     console.log(`${entry.name}: ${entry.duration}ms`);
   });
 });

 // Observe specific entry types
 observer.observe({ entryTypes: ['measure', 'resource', 'navigation'] });

 // Later: disconnect
 observer.disconnect();

Real User Monitoring (RUM):

javascript
 function sendPerformanceMetrics() {
   const navigation = performance.getEntriesByType('navigation')[0];

   const metrics = {
     dns: navigation.domainLookupEnd - navigation.domainLookupStart,
     tcp: navigation.connectEnd - navigation.connectStart,
     ttfb: navigation.responseStart - navigation.requestStart,
     download: navigation.responseEnd - navigation.responseStart,
     domInteractive: navigation.domInteractive - navigation.fetchStart,
     domComplete: navigation.domComplete - navigation.fetchStart,
     loadComplete: navigation.loadEventEnd - navigation.fetchStart
   };

   // Send to analytics
   fetch('/api/metrics', {
     method: 'POST',
     body: JSON.stringify(metrics)
   });
 }

 window.addEventListener('load', () => {
   setTimeout(sendPerformanceMetrics, 0);
 });