The JavaScript Self-Profiling API

November 1, 2020

It's historically been difficult for web developers to understand how the JavaScript in their apps performs in a wide range of cirumstances on real user devices. They've had to instrument code with poorly performing profiling hooks that could slow down page execution, without having the ability to collect stack samples efficiently. This is where the proposed native JavaScript self-profiling API could come in very useful.

This API allows web developers to efficiently identify costly hotspots during page load and user-interactions in their JavaScript. The API also enables you can do things like allocate CPU budgets to individual features implemented on a page, find low-priority code that's executing in the background and wasting power or just client-side work that's unnecessary.

I'm excited for this API as it lets you collect some pretty rich execution data for analysis with relatively low overhead. It also gives you a first-class way to configure a samples profiler so you can set how frequently samples are collected during a session. Here's a commented code-sample of the API in action:

// Begin a new profiling session
// Provide a sampleInterval (period which the session obtains samples)
const profiler = await performance.profile({ sampleInterval: 10 });

// Do some expensive work

// Stop the profiler and return the trace captured
const trace = await profiler.stop();

// Send the trace to an endpoint for reporting

You can follow along progress on the implementation in Chrome on crbug or ChromeStatus and try out the implementation in Chrome Canary if you have the experimental Web Platform features flag turned on.