Sub topic 8
Finding hot spots with @typescript/analyze-trace
This chapter assumes you have already recorded a trace with --generateTrace, as covered in the previous chapter. It also assumes you can read a tsconfig.json and run commands with npx. Here you will turn the raw trace into a short list of places to look at.
Why a tool, and not the raw trace
--generateTrace writes two files into the directory you name:
trace.jsonis a timeline in the Chrome trace format. It has one event per unit of checker work, such as checking a file, an expression, or a type relation.types.jsonis a table of the types the checker created. Events intrace.jsonrefer to types by numeric id, and this table tells you what each id is.
A trace of a real project holds hundreds of thousands of events. Opening it in a timeline viewer is useful, but you have to know where to zoom. @typescript/analyze-trace is a small command-line tool from the TypeScript team that does the first pass for you. It reads both files, finds the longest-running events, and prints them as a tree with the source location and the types involved.
Running it
If you did not record a trace yet, here are both steps:
npx tsc --noEmit --generateTrace traceDir
npx @typescript/analyze-trace traceDirThe tool prints to standard output. For a big project, save the output so you can search it and compare it later:
npx @typescript/analyze-trace traceDir > hotspots-before.txtRecording a trace makes the compile slower. Treat the millisecond values as relative. Compare one hot spot to another, or the same hot spot before and after a fix. Do not compare them to the timings from --extendedDiagnostics.
Reading the output
The report has two kinds of sections. The first lists hot spots. The second, covered below, lists duplicate packages. A hot spot section looks roughly like this. The exact wording and layout vary between versions, so this example is only illustrative.
Hot Spots
└─ Check file /app/src/routes/index.ts (2210ms)
└─ Check variable declaration /app/src/routes/index.ts:41:7 (1980ms)
└─ Check expression /app/src/routes/index.ts:41:20 (1975ms)
└─ Compare types 8812 and 9120 (1790ms)
├─ Type 8812: Paths<AppConfig>
└─ Type 9120: stringRead it from the top down.
- File level. The first line names a file whose check took a long time. This is where you start, because you now know which source file to open.
- Narrowing. Each deeper line is a smaller unit of work inside its parent. A variable declaration contains an expression, and an expression contains a type comparison. The tool follows the branch where most of the time went and stops when the time is spread over many small events.
- The leaf. The deepest line is the best clue. A line number tells you which statement to read. A pair of type ids tells you which types the checker was comparing.
Two readings of the numbers matter:
- A parent's time includes its children's time. In the example, the file took 2210 ms and the comparison inside it took 1790 ms. The comparison is the cause. The file is only where it happened.
- A file with many mildly slow statements shows up as a file with no deep branch. That points to the whole file being expensive. Common causes are a heavy import, or a large generic library type used on every line.
What the type ids mean
The tool usually prints the type's name or a shortened rendering next to each id. When the rendering is cut off, open traceDir/types.json. Each entry has an id, a display string, and often the source location of the declaration. Search for the id to get the full text. Types that are instantiations of a generic, such as Paths<AppConfig>, are the most common suspects.
Tuning what the tool reports
The tool has two thresholds. They let you widen or narrow the report:
--skipMillishides events shorter than the given number of milliseconds. The default is 100.--forceMillisalways reports events longer than the given number, even if the tool would otherwise have skipped them. The default is 500.
# Show more detail: include events down to 20 ms
npx @typescript/analyze-trace traceDir --skipMillis 20
# Show only the worst offenders
npx @typescript/analyze-trace traceDir --skipMillis 400 --forceMillis 1000Run npx @typescript/analyze-trace --help to see the options available in your installed version. They have changed between releases.
If the report is empty, the project has no event above the threshold. This is a good result, and it means the slowness is probably elsewhere. Go back to the phase timings: a large Parse time or I/O Read time points at program scope, not the checker.
A worked example
Suppose the hot spot above points to routes/index.ts line 41:
type Paths<T> = T extends object
? { [K in keyof T & string]: K | `${K}.${Paths<T[K]>}` }[keyof T & string]
: never;
interface AppConfig {
server: { host: string; port: number };
db: { url: string; pool: { min: number; max: number } };
// ...many more nested sections
}
declare function getSetting(path: Paths<AppConfig>): string;
getSetting("db.pool.max");Paths<AppConfig> expands every key path in the whole object, recursively. For a config with a few hundred leaves, that is a union with a few hundred string literals. The checker builds that union again each time it needs to relate it to something. The trace reports the cost at the call site, because that is where the comparison happens, and not at the type alias.
You have several ways to cut the cost:
- Limit the recursion depth with a counter parameter.
- Narrow the type to the sections that callers really need to address.
- Compute the union once and give it a name:
type SettingPath = Paths<AppConfig>;
declare function getSetting(path: SettingPath): string;
declare function hasSetting(path: SettingPath): boolean;A named alias lets the checker cache the result of one instantiation. After the change, record a new trace and run the tool again. The hot spot should shrink or disappear. If it does not, the cost is in the union's size, and you should shrink the union.
The duplicate packages section
After the hot spots, the tool prints a second report that lists packages installed more than once. It lists each package with the different versions and the paths where they live. It matters for performance for two reasons:
- The checker reads and checks each copy as a separate set of declarations, so the parse and check work is multiplied.
- Types from two copies of the same package are not interchangeable. This can cause confusing assignment errors and slow structural comparisons that fail late.
Most often the cause is a version mismatch between your dependencies. Package managers have commands to show why a version was installed, for example npm ls @types/react. You can usually fix duplicates by aligning versions or by using your package manager's overrides or resolutions setting. Reinstall, then record a new trace to confirm that the section is gone.
A workflow you can repeat
Change one thing at a time. If you apply three fixes together and the project gets faster, you do not know which one helped. You also cannot tell whether one of them made things worse.
When the report is not enough
Sometimes the tree ends at a vague event, such as a type comparison where both types render as long unreadable unions. Two techniques help:
- Look up the ids in
types.json. The fulldisplaystring and thefirstDeclarationlocation (when present) show which type alias or interface produced the type. - Open
trace.jsonin a timeline viewer. Chrome'schrome://tracingpage or the Perfetto web viewer will load it. You can then see whether the time is in one long event or many repeated short ones. Many repeated short events on the same file usually mean a type is being re-instantiated again and again, and not that one comparison is hard.
Common errors
- Analyzing the wrong directory. The tool needs the directory that holds
trace.jsonandtypes.json, not a path to one file. A wrong path gives an error or an empty report. - Treating the file at the top as the cause. The file is where the checker was working. The leaf of the tree is closer to the cause.
- Reading times as absolute. Tracing adds overhead. Use before and after comparisons made with the same command and the same machine load.
- Fixing a hot spot in
node_modules. If the leaf is in a library's.d.ts, you cannot edit it. Look for the call site in your code that causes the instantiation, and consider a narrower type argument or an explicit annotation at that point. - Stale traces. If you edit code and run the tool on the old
traceDir, you see the old result. Delete the directory or write to a new one for each run. - Chasing noise. If every event is under your threshold, there is no hot spot to fix. Stop tuning types and look at scope and phase timings.
Exercise
You run npx @typescript/analyze-trace traceDir and the top entry is "Check file src/api/client.ts (3100ms)". Inside it, one nested "Check expression" line at line 88 takes 2900 ms and its deepest child is a comparison of two types, one of which prints as Paths<ApiSchema>. What do you do next, and how do you know the fix worked?
Show answer
Open src/api/client.ts line 88 and find where Paths<ApiSchema> is used. Look up the two type ids in traceDir/types.json if the rendering is cut off. Then reduce the cost, for example by giving Paths<ApiSchema> a named alias, limiting its recursion depth, or narrowing it to the sections callers need. Record a new trace into a fresh directory with the same command, run the tool again, and compare. The 2900 ms event should be much smaller or missing from the report. Check --extendedDiagnostics too, to confirm that the total check time dropped.
Exercise
The report shows no hot spots, but the "Duplicate packages" section lists @types/node in two versions. Is this worth fixing, and why?
Show answer
Yes. The checker parses and checks each copy separately, so the duplicate adds work even when no single event is slow. The two copies can also produce type mismatches between code that uses one version and code that uses the other. Align the versions with your package manager, reinstall, and record a new trace to confirm the section is gone.