Course contentsShow
← JavaScript
Lesson 2088 of 2,72343. DecoratorsFree lesson

Timing and Performance Measurement

Create decorators that measure and report method execution time to identify performance bottlenecks.

Timing and Performance Measurement

What You'll Learn

You'll learn how to create decorators that automatically measure and report how long methods take to execute, helping you spot performance bottlenecks.

Why Measure Method Execution Time?

In complex applications, understanding which methods consume the most time is crucial for optimization. Instead of manually wrapping every method with timing logic, a decorator can do this consistently across your codebase—like installing a speedometer on every function automatically.

Building a Timing Decorator

A timing decorator wraps a method, records the start time, executes the original method, calculates elapsed time, and logs or stores the result:

function measureTime(originalMethod, context) {
  return function(...args) {
    const start = performance.now();
    const result = originalMethod.call(this, ...args);
    const duration = performance.now() - start;
    console.log(`${context.name}() took ${duration.toFixed(2)}ms`);
    return result;
  };
}

class DataProcessor {
  @measureTime
  processLargeArray(data) {
    return data.map(x => x * 2).filter(x => x > 100);
  }
}

For async methods, await the result before measuring:

function measureTimeAsync(originalMethod, context) {
  return async function(...args) {
    const start = performance.now();
    const result = await originalMethod.call(this, ...args);
    const duration = performance.now() - start;
    console.log(`${context.name}() took ${duration.toFixed(2)}ms`);
    return result;
  };
}

Collecting Performance Data

Instead of just logging, you can store timing data for analysis:

const timings = new Map();

function collectTiming(originalMethod, context) {
  return function(...args) {
    const start = performance.now();
    const result = originalMethod.call(this, ...args);
    const duration = performance.now() - start;
    
    if (!timings.has(context.name)) timings.set(context.name, []);
    timings.get(context.name).push(duration);
    
    return result;
  };
}

Key Takeaway: Timing decorators provide automated, consistent performance measurement across methods, making it easy to identify bottlenecks without cluttering your business logic with manual timing code.