TypeScript – window.performance.measure() method (with examples)

Updated: February 14, 2024 By: Guest Contributor Post a comment

Overview

TypeScript, extending JavaScript with types, provides powerful ways to write and manage browser-centric code with additional type safety and tooling support. An invaluable part of building performant web applications is performance monitoring, which often leads developers to the window.performance API, a standard interface for retrieving performance metrics about web page loads and runtime execution. Among its capabilities, the measure() method is a standout feature for calculating precise timings between marks, enabling developers to diagnose and tune their applications. This tutorial explores how to leverage window.performance.measure() in TypeScript, enhanced with type-safety features and examples highlighting its utility from basic techniques to more complex scenarios.

Practical Examples

The window.performance.measure() method records the duration between two marks: start and end. These marks are created using window.performance.mark(). The measure itself can then be inspected in the Performance entry list, accessible via window.performance.getEntriesByType('measure'), providing developers with detailed timing information. Importantly, this feature is supported in most modern browsers, making it a widely available tool for performance diagnostics.

Example 1: Basic Usage

performance.mark('startLoad');
// simulated workload
setTimeout(() => {
  performance.mark('endLoad');
  performance.measure('loadDuration', 'startLoad', 'endLoad');
  const measures = performance.getEntriesByType('measure');
  console.log(measures[0].duration);
}, 1000);

In the example above, two performance marks demarcate the start and end of a simulated workload, such as fetching data from an API or executing complex calculations. After the end mark, window.performance.measure() calculates the elapsed time, and the result is logged, showcasing a simple yet effective diagnostic tool. This practical approach to performance monitoring is foundational for optimizing web applications.

Example 2: Adding Context with Additional Data

performance.mark('initStart');
// Initialization code
setTimeout(() => {
  performance.mark('initEnd');
  performance.measure('initialization', 'initStart', 'initEnd', {
    detail: { task: 'appInit', status: 'success', information: 'Initialization completed successfully' }
  });
  const initMeasure = performance.getEntriesByName('initialization')[0];
  console.log(initMeasure.detail);
}, 500);

This example illustrates how to attach additional data to a measurement, providing context such as the task name, status, and a message. This capability, new in certain browser versions, allows developers to include supplementary details within their timing measurements, enhancing the diagnostics and facilitating more insightful analysis of application performance.

Example 3: Advanced Scenario with Multiple Measurements

performance.mark('taskStart');
// Several tasks are performed here
setTimeout(() => {
  performance.mark('task1End');
  performance.measure('Task 1 Duration', 'taskStart', 'task1End');
}, 150);

setTimeout(() => {
  performance.mark('task2Start');
  performance.measure('Wait Time For Task 2', 'task1End', 'task2Start');
  performance.mark('task2End');
  performance.measure('Task 2 Duration', 'task2Start', 'task2End');

  const allMeasures = performance.getEntriesByType('measure');
  for (let measure of allMeasures) {
    console.log(`${measure.name}: ${measure.duration}`);
  }
}, 300);

This advanced scenario involves multiple sequential tasks, each demarcated using performance marks. Measurements are taken not only for each task’s execution time but also for the intervening time, providing a nuanced view of the system’s behavior. Such granularity is invaluable for identifying performance bottlenecks, especially in applications with complex operations or those that perform tasks in stages.

Conclusion

The window.performance.measure() method, a cornerstone of web performance diagnostics, offers precision and flexibility unmatched by conventional logging or timing methods. By incorporating examples from basic usage to adding context and handling complex scenarios, this guide aims to showcase the method’s utility across varying use cases. Enhanced by TypeScript’s type safety, developers can confidently and accurately assess application performance, ensuring a smoother, faster user experience. As performance becomes an increasingly critical metric, leveraging tools like window.performance.measure() will continue to be essential for modern web development.