Sub topic 9
Recording and reading a performance profile
This chapter assumes you know basic JavaScript, how a browser loads a page, and how to open DevTools and use the Network and Sources panels from earlier chapters. Panel names follow Chromium-based browsers. Firefox has a similar Profiler, and Safari has a Timelines tab.
What the Performance panel answers
The Network panel tells you when resources arrived. The Performance panel tells you what the browser did with the main thread after they arrived. The main thread is the single thread that runs your JavaScript, calculates styles, lays out the page and handles input. If it is busy, the page cannot respond to clicks or paint new frames.
A profile is a recording of that activity over a period of time. You use one when a page feels slow in a way you can't explain from the network, such as janky scrolling, a laggy click or a slow first render.
The panel reports on three kinds of problem:
- Long tasks, where one piece of work blocks the main thread for too long.
- Rendering cost, where style, layout and paint work takes more time than expected.
- Slow responses to input, where the time between a user action and the next frame is too long.
The rendering pipeline in brief
To read a profile you need a rough model of what the browser does to produce a frame. The browser runs JavaScript, recalculates styles, performs layout (working out sizes and positions), paints (drawing pixels into layers) and composites (combining the layers on screen).
A display that refreshes 60 times per second needs a new frame about every 16.7 ms. If JavaScript, layout and paint together take longer than that, the browser drops a frame and the user sees stutter. Changing a property that affects layout, such as width, forces the browser to repeat more of the pipeline than changing transform or opacity, which often only need compositing.
Recording a profile
Open the Performance panel and prepare the recording before you start it. The first three steps matter because they decide how much noise ends up in the data.
- Open the page in an Incognito window so extensions don't add their own activity to the profile.
- In the Performance panel, enable Screenshots so the recording captures how the page looked over time.
- Use the CPU throttling dropdown (for example 4x slowdown) to simulate a slower device. A fast development machine hides problems that phone users will see.
- Click the record button, perform the action you want to study, then click stop.
There are two common ways to record:
| Method | When to use it | What you get |
|---|---|---|
| Record, interact, stop | A specific interaction such as opening a menu or scrolling a list | A focused recording of that action |
| Record and reload (the reload button) | Page load behavior | A recording from navigation until the page settles |
Keep recordings short. A 5 second recording of one action is easier to read than a 60 second one that includes your pauses and mouse movements.
Reading the profile
After you stop recording, the panel shows several regions. Learn what each one is for.
- Overview. A strip at the top with a chart of CPU activity, frames per second and screenshots. Drag across it to select the time range you want to study. The rest of the panel then zooms to that range.
- Tracks. Rows in the main area. Common ones are Frames, Interactions, Timings, Network and Main. The Main track is the one you will spend the most time in.
- Flame chart. The Main track draws each task as a stack of bars. The top bar is the task. Bars below it are functions or browser work that the task called. Wider bars took more time.
- Bottom panel. Tabs such as Summary, Bottom-Up, Call Tree and Event Log. They show the same data as tables, so you can sort and total it.
Colors in the flame chart
The panel colors activity by category. The exact shades can change between versions, so check the Summary tab's legend, but the grouping is stable:
| Category | Typical color | Meaning |
|---|---|---|
| Scripting | Yellow | JavaScript execution |
| Rendering | Purple | Style recalculation and layout |
| Painting | Green | Paint and compositing work |
| System | Gray | Browser internals |
| Idle | White | The main thread had nothing to do |
A profile dominated by yellow points toward your JavaScript. A lot of purple points toward layout and style work. A mostly white profile means the main thread was not the bottleneck, so look at the network or at work off the main thread.
Long tasks
A long task is any main-thread task that runs for more than 50 ms. DevTools marks these in the Main track with a red triangle in the corner of the task bar and a red hatched region for the time beyond 50 ms. While a long task runs, the browser cannot respond to input. Finding and splitting long tasks is the most common outcome of a profiling session.
Click a long task to see its details in the Summary tab. The Call Tree and Bottom-Up tabs help you find which functions took the time:
- Call Tree starts from the root of the task and goes down into the functions it called. Use it to follow the path of execution.
- Bottom-Up starts from the functions that spent the most self time and works up to their callers. Self time is the time spent in a function's own code, excluding the functions it called. Use it to find the most expensive single function.
Total time and self time are different. A function that calls other expensive functions has a large total time and a small self time. The place to optimize is usually where self time is large.
A worked example
The following page-level code builds a list of 1,000 items and attaches it to the document. It marks the start and end of the work using the User Timing API, so the work appears in the Timings track.
performance.mark('render-start');
const list = document.createElement('ul');
for (let i = 0; i < 1000; i++) {
const item = document.createElement('li');
item.textContent = 'Item ' + i;
list.appendChild(item);
}
document.body.appendChild(list);
performance.mark('render-end');
performance.measure('render-list', 'render-start', 'render-end');performance.mark() records a named timestamp. performance.measure() creates a named span between two marks. With the profile recording, DevTools draws a bar labeled render-list in the Timings track. You can read your own code's duration next to the browser's work in the Main track.
To try it:
- Open any page, then open the Performance panel and click record.
- Paste the code into the Console and press Enter.
- Wait a moment, then stop the recording.
- Find the
render-listbar in the Timings track and click it to see its duration. - Look at the Main track under the same time range. You should see a task for the Console evaluation with scripting time. You may also see style recalculation and layout after it, because the new elements changed the page.
Because the list is built in a detached ul and attached once, the browser only lays out the page once for these 1,000 items. If you change the code to call document.body.appendChild(item) inside the loop and then read document.body.offsetHeight on each pass, the profile will show many layout events in purple. That pattern is called layout thrashing, and it is covered below.
Layout thrashing
Layout thrashing happens when code alternates between writing to the DOM and reading a layout value such as offsetHeight or getBoundingClientRect(). A read forces the browser to compute layout immediately so the value is accurate. If a write invalidated the layout just before, each read triggers a fresh layout. DevTools flags this in the flame chart as a "Forced reflow" warning on the task.
The fix is to batch: do all reads first, then all writes.
const boxes = document.querySelectorAll('.box');
// Slow: each iteration writes, then the next read forces layout.
boxes.forEach((box) => {
const width = box.offsetWidth;
box.style.width = width + 10 + 'px';
});
// Faster: read everything first, then write.
const widths = Array.from(boxes, (box) => box.offsetWidth);
boxes.forEach((box, i) => {
box.style.width = widths[i] + 10 + 'px';
});In the first loop, the write to style.width in one iteration makes the layout stale. The offsetWidth read in the next iteration forces a recalculation. In the second version, all reads happen against one valid layout, and the browser lays out once after the writes.
Interactions and frames
The Frames track shows each frame the browser produced. A green block is a frame that was presented on time. A red or hatched marker indicates a dropped or partially presented frame. Hover over a frame to see its duration and the effective frame rate.
The Interactions track lists user inputs such as clicks and key presses. Each one is divided into three parts:
- Input delay: the time the event waited because the main thread was busy.
- Processing time: the time your event handlers ran.
- Presentation delay: the time from the end of the handlers until the next frame was painted.
These three parts add up to the interaction's total latency, the quantity behind the Interaction to Next Paint (INP) metric. If the input delay is large, a long task was running when the user clicked. If processing time is large, your handler is the problem. If presentation delay is large, rendering work after the handler is the cost.
Common mistakes
- Profiling in a development build with extensions on. Extensions and unminified framework code add work that real users don't have. Use an Incognito window and, when possible, a production build.
- Skipping throttling. A profile on a fast laptop may show no long tasks at all. Throttle the CPU to expose them.
- Optimizing by total time. A wide bar at the top of a call stack is mostly the time of its children. Check self time in Bottom-Up before changing a function.
- Recording too much. Long recordings are slow to load and hard to read. Record one action at a time.
- Trusting one run. Timing varies from run to run. Compare several recordings before and after a change.
- Confusing the profile with network timing. If the Main track is mostly idle, the delay is probably waiting for data, so go back to the Network panel.
A repeatable workflow
- Reproduce the problem and decide on one action to record.
- Set CPU throttling, turn on Screenshots, and use Incognito.
- Record only that action, then stop.
- Select the time range of the problem in the Overview.
- Look at the Main track for long tasks, forced reflow warnings and the dominant color.
- Use Bottom-Up to find the functions with the highest self time, and Call Tree to see who called them.
- Make one change.
- Record again under the same conditions and compare.
Exercise
You record a click on a menu button. The Interactions track shows a total latency of 400 ms. The breakdown is input delay 20 ms, processing time 350 ms, and presentation delay 30 ms. In Bottom-Up, one function called filterItems has a self time of 320 ms. Which part of the interaction should you work on, and what would you do first?
Show answer
Work on processing time, since your event handler accounts for 350 of the 400 ms. Start with filterItems, which has the highest self time (320 ms). Look at what it does, for example nested loops over a large array or repeated DOM reads and writes, and reduce that work. Options include caching results, filtering less data, or splitting the work into smaller chunks so the main thread can paint in between. Then record again with the same CPU throttling to confirm the latency drops.
Exercise
A loop reads element.offsetHeight and then sets element.style.height on each pass. The profile shows many purple Layout events and "Forced reflow" warnings. What is happening, and how do you fix it?
Show answer
This is layout thrashing. Each write invalidates the layout, and the next read forces the browser to recompute it immediately. Fix it by separating the phases: read all the heights first into an array, then perform all the writes. The browser then calculates layout once for the reads and once after the writes.
Exercise
You record a slow page load and the Main track is mostly white (idle) with a few short tasks, yet the page appears late. Which panel should you check next, and why?
Show answer
Check the Network panel. A mostly idle main thread means the browser was waiting rather than computing, usually for a slow or blocked request. The Network waterfall shows which resource arrived late and why, for example a long server wait or a render-blocking file.