Sub topic 2
Measuring before optimizing
This chapter assumes you can run tsc from the command line, read and edit a tsconfig.json, and know the four stages of the compiler pipeline: parse, bind, check, and emit. You don't need a monorepo yet. The goal here is to get a trustworthy baseline before you change any build settings.
Why measure first
Build time has several possible causes, and each has a different fix. A project with slow type checking benefits from incremental. A project with slow declaration emit benefits from isolatedDeclarations. A project that spends most of its time loading files needs a smaller include or fewer @types packages. If you apply a fix without knowing which cause you have, you may add complexity and gain nothing.
Measuring also gives you a number to compare against. Without a baseline, "the build feels faster" is the only evidence you have that a change worked.
Reading --extendedDiagnostics
The --extendedDiagnostics flag makes tsc print statistics after the build finishes. Run it from the directory that holds your tsconfig.json:
tsc -p . --extendedDiagnostics
# run it twice: the second run should report less check time
tsc -p . --extendedDiagnosticsThe second command is a useful habit. With no incremental state on disk, both runs should look similar. Once you enable incremental in a later chapter, the second run is where you see the difference.
The output looks roughly like this. Your numbers will differ.
Files: 412
Lines of Library: 38024
Lines of Definitions: 121377
Lines of TypeScript: 54210
Lines of JavaScript: 0
Identifiers: 98532
Symbols: 210044
Types: 95310
Instantiations: 412876
Memory used: 412345K
I/O Read time: 0.21s
Parse time: 0.88s
ResolveModule time: 0.19s
Program time: 1.41s
Bind time: 0.40s
Check time: 4.72s
transformTime time: 0.35s
Source Map time: 0.00s
Emit time: 0.61s
Total time: 7.14sThe exact set of lines changes between TypeScript versions, so treat the list above as an example and not a contract.
What each group of numbers tells you
Counts
The first block describes the size of the program.
- Files is every file the compiler loaded. This includes your sources, the default library files such as
lib.es2022.d.ts, and every.d.tsfile pulled in fromnode_modules. - Lines of Definitions counts lines in
.d.tsfiles. If this number is much larger than Lines of TypeScript, most of the compiler's work is on code you didn't write. - Types, Symbols, and Instantiations describe the work of the checker. A very high instantiation count relative to the line count often points to heavy generics or large union types.
Timings
The timing block maps onto the pipeline.
| Line | Pipeline stage | What dominates it |
|---|---|---|
| I/O Read time, Parse time | Parse | Number and size of files loaded |
| ResolveModule time | Parse (module lookup) | Slow file systems, deep `node_modules` |
| Bind time | Bind | Usually small |
| Check time | Check | Type complexity, number of files |
| Emit time, transformTime | Emit | Declaration output, source maps |
| Total time | All | Sum of the above plus startup |
In most application code, Check time is the largest line by a wide margin. In that case, the stage worth optimizing is checking, and incremental is the first tool to try. If instead Parse time is large and Files is surprisingly high, the program contains files you didn't expect, and you should look at that before anything else.
Memory
Memory used matters on CI runners with limited RAM. If it approaches the machine's limit, builds can slow down from garbage collection or fail outright. Compare it before and after any change, the same as you do time.
Finding out why files are included
When the file count is higher than you expect, ask the compiler to explain it:
tsc -p . --listFilesOnly
tsc -p . --explainFiles--listFilesOnly prints every file in the program and stops, without emitting. --explainFiles adds the reason each file was included, such as "Matched by include pattern" or "Imported via './util' from file 'src/index.ts'".
Common surprises are:
- An
includepattern that matches test files, build scripts, or generated code. - Every package under
node_modules/@typesloaded automatically, even when your code uses only a few of them. Thetypescompiler option restricts this. - A single large dependency whose
.d.tsfiles drag in a long chain of other declarations.
{
"compilerOptions": {
"types": ["node"],
"skipLibCheck": true
},
"include": ["src"]
}Setting types to an explicit list stops tsc from loading every @types package. skipLibCheck skips type checking of .d.ts files, which cuts Check time at the cost of not reporting errors inside declaration files. Both are quick wins, but apply them one at a time and measure each, so you know which one helped.
Seeing where the checker spends time
--extendedDiagnostics tells you which stage is slow. It doesn't tell you which file or type is responsible. For that, use the tracing flag:
tsc -p . --generateTrace ./traceThis writes trace.json and types.json into the trace directory. You can load trace.json into a Chromium-based browser at chrome://tracing, or into the Perfetto UI, and see a timeline of how long the checker spent on each file. Long bars point to the files worth investigating. The types.json file lists the types the checker created, which helps when one expression generates a huge number of them.
Tracing slows the build and produces large files, so use it to investigate a problem you have already identified. Don't run it as part of every build.
Getting a reliable baseline
A single timing is easy to misread. Several things add noise:
- Cold versus warm file cache. The first run after a reboot or a branch switch reads files from disk. Later runs read them from the operating system's cache and are faster.
- Other work on the machine. An editor running its own TypeScript server, a test watcher, or a browser can change timings by a large margin.
- Existing incremental state. If a
.tsbuildinfofile is already on disk, a "baseline" run may not do the full work.
A practical procedure:
- Close or pause other heavy processes.
- Delete the output directory and any
.tsbuildinfofiles so no earlier state is reused. - Run the build once and discard the result to warm the file cache.
- Delete the output and build info again.
- Run the build three to five times, clearing state between runs, and record Check time and Total time each time.
- Use the median, not the best or average.
You can script this so the steps are the same every time:
#!/usr/bin/env bash
set -euo pipefail
runs=5
for i in $(seq 1 "$runs"); do
rm -rf dist .cache
tsc -p . --extendedDiagnostics | grep -E '^(Check time|Total time|Memory used)'
doneThe rm -rf dist .cache line matches the outDir and tsBuildInfoFile paths used in this tutorial's example config. Change it to match yours. Double-check the paths before running a recursive delete.
Comparing before and after
When you change an option, repeat the same procedure and compare the same lines. Keep a small table so the results are easy to read later:
| Change | Check time (median) | Total time (median) | Memory used |
|---|---|---|---|
| Baseline | 4.72s | 7.14s | 412 MB |
| `types: ["node"]` | 3.90s | 6.02s | 351 MB |
| `skipLibCheck: true` | 2.15s | 4.18s | 340 MB |
The numbers above are illustrative. What matters is the habit: one change per row, the same measurement each time.
For the later chapters, remember which scenario you are testing:
- A cold build has no previous state.
incrementaldoesn't help it, and might make it slightly slower because it must also write the build info file. - A warm build after a small edit is where
incrementalhelps most. - A CI build is usually a cold build unless you restore cached state, which a later chapter covers.
Common errors when measuring
- Timing the editor, not the compiler. The editor's TypeScript server has its own performance profile. Use the command line for build measurements.
- Using
--watchfor baselines. Watch mode keeps the program in memory, so its numbers aren't comparable to a freshtscrun. - Comparing runs with different flags.
--extendedDiagnosticsitself adds a small cost. Use it in every run you compare, or in none. - Changing two things at once. If Check time falls after you enable
incrementaland also editinclude, you can't say which change did it. - Ignoring
--noEmitdifferences. A run with--noEmitskips emit, so its Total time isn't comparable to a full build. Compare like with like.
Exercise
You run tsc -p . --extendedDiagnostics and see Files: 3400, Lines of TypeScript: 9000, Lines of Definitions: 600000, Parse time: 6.1s, and Check time: 3.0s. Which stage is the biggest cost, and what should you investigate first, before enabling any build option?
Show answer
Parse time (6.1s) is larger than Check time (3.0s). The very large Lines of Definitions and Files counts show that the program loads far more declaration files than your 9000 lines of source would need. Run tsc -p . --explainFiles to see why each file is included, then check whether types should be restricted or whether include matches unwanted directories. Enabling incremental first would not address the main cost, since the time goes into loading files.
Exercise
Why should you delete the .tsbuildinfo file and output directory between baseline runs, and why should you take the median of several runs?
Show answer
A leftover .tsbuildinfo file lets tsc reuse earlier results, so the run no longer measures the full build. Deleting it makes each run start from the same cold state. Single runs are affected by file cache warmth and other processes on the machine, so the median of several runs gives a more stable figure than any one run, the best run, or the average.