JavaScript Easy technical 0 views 2 min read

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

Peer-reviewed by HireXTech Technical Panel Updated for 2025/2026 hiring Editorial standards
Practise this track
Interviewer Expectations for this Question
01
Core Competency

Assesses fundamental understanding of JavaScript conventions, runtime behavior, and memory/performance considerations.

02
Evaluation Criteria

Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.

Comprehensive Model Answer Verified Solution

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

Basic timing:

     // 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:

     // 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:

     // 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:

     // 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:

     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):

     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):

     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);
     });
     

Candidate Response Strategy & Interview Tips

  1. Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
  2. Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
  3. Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
  4. Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.
Related Topics & Skills
Spotted an error or have an alternative solution?