Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 86

Profiling with the Performance API

This lesson is built with resources from developer.mozilla.org and youtube.com.

Hello! Welcome back to our module on Memory Management and Performance Profiling.

In our last lesson, we implemented the Object Pool pattern—a powerful optimization to reduce the performance cost of frequent object creation and destruction. But a key principle in optimization is "measure, don't guess." How can we be sure our object pool is actually faster? How much faster is it?

This brings us to today's topic. Your goal is to learn how to measure script execution time with high precision using the Performance API. This is a fundamental skill for any developer serious about performance, allowing you to benchmark code, validate optimizations, and make data-driven decisions. We will explore why the traditional Date.now() is unsuitable for this task and dive into the modern, high-precision tools provided by the browser.

The Problem with Date.now()

For years, the simplest way to time a JavaScript operation was to subtract two Date.now() timestamps.

const start = Date.now();
// ... some expensive operation ...
const end = Date.now();
console.log(`Operation took ${end - start} milliseconds.`);

However, this method has two critical flaws for performance measurement:

  1. Low Resolution: Date.now() returns the time in whole milliseconds. Modern processors can execute millions of operations in a single millisecond, making it impossible to accurately measure very fast functions. The duration might simply round down to 0ms.
  2. Not Monotonic: The clock used by Date.now() is the system clock, which can be adjusted. It can be synchronized with an external time server, or even changed manually by the user. This means it's possible for Date.now() to jump forwards or even backwards, leading to inaccurate or nonsensical measurements.

A monotonic clock, by contrast, is guaranteed to only move forward and at a constant rate, making it perfect for measuring elapsed time intervals.


High-Precision Timing with performance.now()

The Performance API was introduced to solve these problems. It provides a high-resolution, monotonic timer through the performance.now() method.

To understand the key differences and the underlying mechanics, the following reading from the Mozilla Developer Network (MDN) is essential.

High precision timing - Web APIs | MDN

Let's begin by establishing the theoretical foundation for high-precision timing. This MDN article clearly explains why the Performance API is superior to Date for benchmarking.

Please read the sections titled 'High precision timing', 'DOMHighResTimeStamp', 'Performance.now() vs. Date.now()', and 'Time origins'. Focus on the comparison table, which perfectly summarizes the advantages of performance.now(). Also, take note of the concept of timeOrigin, the stable reference point for all performance measurements.

As you've just read, performance.now() provides a timestamp in milliseconds with sub-millisecond precision (a DOMHighResTimeStamp). This value represents the time elapsed since performance.timeOrigin—typically the start of the page navigation. This stable origin and monotonic progression make it the standard for reliable performance measurement.

Let's see it in action. If you open your browser's developer console and type performance.now(), you'll get a value like 233936.400000001. The decimal part is the sub-millisecond precision that Date.now() lacks.


Going Beyond Simple Timestamps: mark() and measure()

While taking two performance.now() timestamps is a big improvement, the Performance API offers a more powerful and semantic way to benchmark your code: marks and measures.

  • performance.mark(name): Creates a named timestamp in the browser's performance timeline. Think of it as planting a named flag at a specific point in your code's execution.
  • performance.measure(name, startMark, endMark): Calculates the duration between two marks and creates a named "measure" entry in the timeline.

This approach is incredibly useful for two reasons:

  1. It gives your measurements meaningful names, making your code and performance data easier to understand.
  2. These marks and measures are automatically integrated into the browser's developer tools, allowing you to visualize your custom timings alongside other performance data like rendering and network activity.

The following video provides an excellent demonstration of this concept.

The Awesome Web Performance APIs - Dan Shappir

To see the power of marks and measures in a real-world context, let's watch this segment from a talk on Web Performance APIs by Dan Shappir.

Watch the section from 25:09 to 31:30. The speaker explains how performance.mark() and performance.measure() work together and, crucially, shows how these custom timings appear directly in tools like WebPageTest and the Chrome DevTools Performance tab. This will help you connect the code you write to the analysis you can perform.

As the video showed, creating these semantic measurements allows you to overlay your application's specific logic (e.g., "process-user-data") onto the generic performance timeline, which is invaluable for debugging and analysis.


Putting It All Together: A Practical Example

Let's use our new tools to benchmark the Object Pool pattern from the previous lesson.

First, we define two functions: one that creates a large number of objects naively, and one that uses our object pool.

// Assume the Vector2D and VectorPool classes from the previous lesson exist

// --- Naive Approach ---
function runNaive(iterations) {
  for (let i = 0; i < iterations; i++) {
    const tempVec = new Vector2D(i, i);
    // ... do some work with tempVec ...
  }
}

// --- Object Pool Approach ---
const pool = new VectorPool(10000); // Pre-allocate a large pool
function runWithPool(iterations) {
  for (let i = 0; i < iterations; i++) {
    const tempVec = pool.acquire();
    tempVec.reset(i, i);
    // ... do some work with tempVec ...
    pool.release(tempVec);
  }
}

Now, let's measure them using mark and measure.

const ITERATIONS = 500_000;

// Measure the naive approach
performance.mark('naive-start');
runNaive(ITERATIONS);
performance.mark('naive-end');
performance.measure('Naive Method', 'naive-start', 'naive-end');

// Measure the pool approach
performance.mark('pool-start');
runWithPool(ITERATIONS);
performance.mark('pool-end');
performance.measure('Object Pool Method', 'pool-start', 'pool-end');

// Retrieve and log the results
const measures = performance.getEntriesByType('measure');
measures.forEach(measure => {
  console.log(`${measure.name}: ${measure.duration.toFixed(3)}ms`);
});

// Clean up the marks and measures if you want to run again
performance.clearMarks();
performance.clearMeasures();

When you run this code in your browser's console, you'll see a significant difference in the reported durations. The performance.measure() method gives you a PerformanceMeasure object containing the duration and other details.

For a deeper look into the capabilities of performance.measure(), the MDN documentation is the best reference.

Performance: measure() method - Web APIs - MDN Web Docs

The measure method is quite flexible. This MDN page details its various syntaxes and options.

Skim through the 'Examples' section. You don't need to memorize everything, but notice how you can pass in timestamps directly, or include arbitrary metadata using the detail property. This can be useful for adding context to your performance measurements.

Test your understanding!

You are comparing two sorting algorithms: a naive Bubble Sort and the native Array.prototype.sort().

Write a function benchmarkSort(arraySize) that:

  1. Creates a large, randomly-filled array of numbers.
  2. Creates a copy of the array for each algorithm to use.
  3. Uses performance.mark() and performance.measure() to time how long each sorting algorithm takes to sort its copy of the array. The measures should be named 'Bubble Sort' and 'Native Sort'.
  4. Uses performance.getEntriesByName() to retrieve the two PerformanceMeasure objects.
  5. Logs the duration of each sort to the console, formatted to three decimal places.
Show answer

Here is a possible solution:

function bubbleSort(arr) {
  const n = arr.length;
  for (let i = 0; i < n - 1; i++) {
    for (let j = 0; j < n - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
      }
    }
  }
  return arr;
}

function benchmarkSort(arraySize) {
  // 1. Create a large, randomly-filled array
  console.log(`--- Benchmarking with ${arraySize} items ---`);
  const randomArray = Array.from({ length: arraySize }, () => Math.random() * arraySize);
  
  // 2. Create copies for each algorithm
  const arrayForBubble = [...randomArray];
  const arrayForNative = [...randomArray];

  // 3. Time Bubble Sort
  performance.mark('bubble-start');
  bubbleSort(arrayForBubble);
  performance.mark('bubble-end');
  performance.measure('Bubble Sort', 'bubble-start', 'bubble-end');

  // 3. Time Native Sort
  performance.mark('native-start');
  arrayForNative.sort((a, b) => a - b); // Native sort needs a comparator for numbers
  performance.mark('native-end');
  performance.measure('Native Sort', 'native-start', 'native-end');

  // 4. Retrieve the measures
  const bubbleMeasure = performance.getEntriesByName('Bubble Sort')[0];
  const nativeMeasure = performance.getEntriesByName('Native Sort')[0];

  // 5. Log the results
  console.log(`Bubble Sort took: ${bubbleMeasure.duration.toFixed(3)}ms`);
  console.log(`Native Sort took: ${nativeMeasure.duration.toFixed(3)}ms`);

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

// Run the benchmark
benchmarkSort(10000);

Conclusion

You now have a robust and precise toolkit for measuring the performance of your JavaScript code. This is the first step in any optimization process: establishing a baseline and verifying the impact of your changes.

Key Takeaways:

  • For performance benchmarking, always prefer performance.now() over Date.now(). It offers high-resolution, sub-millisecond precision and is based on a monotonic clock that isn't affected by system time adjustments.
  • The performance.mark(name) method allows you to set named timestamps at key points in your application's lifecycle.
  • The performance.measure(name, startMark, endMark) method provides a semantic way to measure the duration between two marks, creating an entry in the performance timeline.
  • These custom marks and measures are visible in the browser's performance profiling tools, enabling you to correlate your application's logic with other runtime events.

In our next lesson, we will move from measuring specific, targeted operations to analyzing the overall performance of your application. We will learn how to profile CPU usage with the browser's performance profiler to identify performance bottlenecks, helping you find where to focus your optimization efforts.