Performance Microsoft - TypeScript Wiki
Performance Microsoft - TypeScript Wiki
microsoft / TypeScript
Code Issues 4.8k Pull requests 279 Actions Projects 8 Wiki Security Insights
Performance
Jump to bottom
showConfig
traceResolution
https://github.com/microsoft/TypeScript/wiki/Performance#controlling-types-inclusion 1/11
2/10/2021 Performance · microsoft/TypeScript Wiki
However, and as soon as you need to compose two or more types, you have the option of extending those types with an interface, or intersecting them
in a type alias, and that's when the differences start to matter.
Interfaces create a single flat object type that detects property conflicts, which are usually important to resolve! Intersections on the other hand just
recursively merge properties, and in some cases produce never . Interfaces also display consistently better, whereas type aliases to intersections can't be
displayed in part of other intersections. Type relationships between interfaces are also cached, as opposed to intersection types as a whole. A final
noteworthy difference is that when checking against a target intersection type, every constituent is checked before checking against the
"effective"/"flattened" type.
For this reason, extending types with interface s/ extends is suggested over creating intersection types.
interface WeekdaySchedule {
day: "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday";
wake: Time;
startWork: Time;
endWork: Time;
sleep: Time;
}
interface WeekendSchedule {
day: "Saturday" | "Sunday";
wake: Time;
familyMeal: Time;
sleep: Time;
}
However, they also come with a cost. Every time an argument is passed to printSchedule , it has to be compared to each element of the union. For a
two-element union, this is trivial and inexpensive. However, if your union has more than a dozen elements, it can cause real problems in compilation
speed. For instance, to eliminate redundant members from a union, the elements have to be compared pairwise, which is quadratic. This sort of check
might occur when intersecting large unions, where intersecting over each union member can result in enormous types that then need to be reduced.
One way to avoid this is to use subtypes, rather than unions.
https://github.com/microsoft/TypeScript/wiki/Performance#controlling-types-inclusion 2/11
2/10/2021 Performance · microsoft/TypeScript Wiki
interface Schedule {
day: "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday" | "Saturday" | "Sunday";
wake: Time;
sleep: Time;
}
A more realistic example of this might come up when trying to model every built-in DOM element type. In this case, it would be preferable to create a
base HtmlElement type with common members, which DivElement , ImgElement , etc. extend, rather than to create the exhaustive union DivElement |
/*...*/ | ImgElement | /*...*/ .
There are some very basic ways of breaking up a codebase into projects. As an example, one might be a program with a project for the client, a project
for the server, and a project that's shared between the two.
------------
| |
| Shared |
^----------^
/ \
/ \
------------ ------------
| | | |
| Client | | Server |
-----^------ ------^-----
------------
| |
| Shared |
^-----^----^
/ | \
/ | \
------------ ------------ ------------
| | | Shared | | |
| Client | | Tests | | Server |
-----^------ ------------ ------^-----
| |
| |
------------ ------------
| Client | | Server |
| Tests | | Tests |
------------ ------------
One commonly asked question is "how big should a project be?". This is a lot like asking "how big should a function be?" or "how big should a class be?"
and, to a large extent, it comes down to experience. One familiar way of splitting up JS/TS code is with folders. As a heuristic, if things are related enough
to go in the same folder, they belong in the same project. Beyond that, avoid massive or tiny projects. If one project is larger than all the others
combined, that's a warning sign. Similarly, it's best to avoid having dozens of single-file projects because the overhead adds up.
https://github.com/microsoft/TypeScript/wiki/Performance#controlling-types-inclusion 3/11
2/10/2021 Performance · microsoft/TypeScript Wiki
You can read up more about project references here.
Specifying Files
You should always make sure that your configuration files aren't including too many files at once.
The primary difference between the two is that files expects a list of file paths to source files, and include / exclude use globbing patterns to match
against files.
While specifying files will allow TypeScript to quickly load up files up directly, it can be cumbersome if you have many files in your project without just
a few top-level entry-points. Additionally, it's easy to forget to add new files to your tsconfig.json , which means that you might end up with strange
editor behavior where those new files are incorrectly analyzed. All this can be cumbersome.
include / exclude help avoid needing to specify these files, but at a cost: files must be discovered by walking through included directories. When
running through a lot of folders, this can slow compilations down. Additionally, sometimes a compilation will include lots of unnecessary .d.ts files and
test files, which can increase compilation time and memory overhead. Finally, while exclude has some reasonable defaults, certain configurations like
mono-repos mean that a "heavy" folders like node_modules can still end up being included.
Specify only input folders in your project (i.e. folders whose source code you want to include for compilation/analysis).
Don't mix source files from other projects in the same folder.
If keeping tests in the same folder as other source files, give them a distinct name so they can easily be excluded.
Avoid large build artifacts and dependency folders like node_modules in source directories.
Note: without an exclude list, node_modules is excluded by default; as soon as one is added, it's important to explicitly add node_modules to the list.
{
"compilerOptions": {
// ...
},
"include": ["src"],
"exclude": ["**/node_modules", "**/.*/"],
}
By default, TypeScript automatically includes every @types package that it finds in your node_modules folder, regardless of whether you import it. This is
meant to make certain things "just work" when using Node.js, Jasmine, Mocha, Chai, etc. since these tools/packages aren't imported - they're just loaded
into the global environment.
Sometimes this logic can slow down program construction time in both compilation and editing scenarios, and it can even cause issues with multiple
global packages with conflicting declarations, causing errors like
In cases where no global package is required, the fix is as easy as specifying an empty field for the "types" option in a tsconfig.json / jsconfig.json
https://github.com/microsoft/TypeScript/wiki/Performance#controlling-types-inclusion 4/11
2/10/2021 Performance · microsoft/TypeScript Wiki
// src/tsconfig.json
{
"compilerOptions": {
// ...
If you still need a few global packages, add them to the types field.
// tests/tsconfig.json
{
"compilerOptions": {
// ...
Incremental compiles are enabled by default when using the composite flag for project references, but can bring the same speed-ups for any project
that opts in.
By default, TypeScript performs a full re-check of all .d.ts files in a project to find issues and inconsistencies; however, this is typically unnecessary.
Most of the time, the .d.ts files are known to already work - the way that types extend each other was already verified once, and declarations that
matter will be checked anyway.
TypeScript provides the option to skip type-checking of the .d.ts files that it ships with (e.g. lib.d.ts ) using the skipDefaultLibCheck flag.
Alternatively, you can also enable the skipLibCheck flag to skip checking all .d.ts files in a compilation.
These two options can often hide misconfiguration and conflicts in .d.ts files, so we suggest using them only for faster builds.
Is a list of dogs a list of animals? That is, is List<Dog> assignable to List<Animals> ? The straightforward way to find out is to do a structural comparison
of the types, member by member. Unfortunately, this can be very expensive. However, if we know enough about List<T> , we can reduce this
assignability check to determining whether Dog is assignable to Animal (i.e. without considering each member of List<T> ). (In particular, we need to
know the variance of the type parameter T .) The compiler can only take full advantage of this potential speedup if the strictFunctionTypes flag is
enabled (otherwise, it uses the slower, but more lenient, structural check). For this reason, we recommend building with --strictFunctionTypes (which is
enabled by default under --strict ).
Make sure that in addition to reading this section, you read up about performance in your choice of build tool - for example:
https://github.com/microsoft/TypeScript/wiki/Performance#controlling-types-inclusion 5/11
2/10/2021 Performance · microsoft/TypeScript Wiki
Concurrent Type-Checking
Type-checking typically requires information from other files, and can be relatively expensive compared to other steps like transforming/emitting code.
Because type-checking can take a little bit longer, it can impact the inner development loop - in other words, you might experience a longer
edit/compile/run cycle, and this might be frustrating.
For this reason, some build tools can run type-checking in a separate process without blocking emit. While this means that invalid code can run before
TypeScript reports an error in your build tool, you'll often see errors in your editor first, and you won't be blocked for as long from running working code.
An example of this in action is the fork-ts-checker-webpack-plugin plugin for Webpack, or awesome-typescript-loader which also sometimes does this.
The need for features that need non-local information is somewhat rare - regular enum s can be used in place of const enum s, and modules can be used
instead of namespace s. For that reason, TypeScript provides the isolatedModules flag to error on features powered by non-local information. Enabling
isolatedModules means that your codebase is safe for tools that use TypeScript APIs like transpileModule or alternative compilers like Babel.
As an example, the following code won't properly work at runtime with isolated file transforms because const enum values are expected to be inlined;
but luckily, isolatedModules will tell us that early on.
// ./src/fileA.ts
// ./src/fileB.ts
console.log(E.A);
// ~
// error: Cannot access ambient const enums when the '--isolatedModules' flag is provided.
Remember: isolatedModules doesn't automatically make code generation faster - it just tells you when you're about to use a feature that might
not be supported. The thing you're looking for is isolated module emit in different build tools and APIs.
ts-loader provides a transpileOnly flag which performs isolated file emit by using transpileModule .
awesome-typescript-loader provides a transpileOnly flag which performs isolated file emit by using transpileModule .
TypeScript's transpileModule API can be used directly.
awesome-typescript-loader provides the useBabel flag.
babel-loader compiles files in an isolated manner (but does not provide type-checking on its own).
gulp-typescript enables isolated file emit when isolatedModules is enabled.
rollup-plugin-typescript only performs isolated file compilation.
ts-jest can use be configured with the [ isolatedModules flag set to true ]isolatedModules: true(.
ts-node can detect the "transpileOnly" option in the "ts-node" field of a tsconfig.json , and also has a --transpile-only flag.
Investigating Issues
There are certain ways to get hints of what might be going wrong.
https://github.com/microsoft/TypeScript/wiki/Performance#controlling-types-inclusion 6/11
2/10/2021 Performance · microsoft/TypeScript Wiki
Certain editors also have their own troubleshooting guides for performance, so consider reading up on them. For example, Visual Studio Code has its
own page for Performance Issues as well.
extendedDiagnostics
You can run TypeScript with --extendedDiagnostics to get a printout of where the compiler is spending its time.
Files: 6
Lines: 24906
Nodes: 112200
Identifiers: 41097
Symbols: 27972
Types: 8298
Memory used: 77984K
Assignability cache size: 33123
Identity cache size: 2
Subtype cache size: 0
I/O Read time: 0.01s
Parse time: 0.44s
Program time: 0.45s
Bind time: 0.21s
Check time: 1.07s
transformTime time: 0.01s
commentTime time: 0.00s
I/O Write time: 0.00s
printTime time: 0.01s
Emit time: 0.01s
Total time: 1.75s
Note that Total time won't be the sum of all times preceding it, since there is some overlap and some work is not instrumented.
Field Meaning
Files the number of files that the program is including (use --listFiles to see what they are).
I/O Read
time spent reading from the file system - this includes traversing include 'd folders.
time
combined time spent performing reading from the file system, scanning and parsing the program, and other calculation of the
Program time program graph. These steps are intermingled and combined here because files need to be resolved and loaded once they're
included via import s and export s.
Bind time Time spent building up various semantic information that is local to a single file.
transformTime
Time spent rewriting TypeScript ASTs (trees that represent source files) into forms that work in older runtimes.
time
I/O Write
Time spent writing/updating files on disk.
time
printTime Time spent calculating the string representation of an output file and emitting it to disk.
Does the number of files/number of lines of code roughly correspond to the number of files in your project? Try running --listFiles if not.
Does Program time or I/O Read time seem fairly high? Ensure your include / exclude settings are configured correctly.
Do other times seem off? You might want to file an issue! Things you can do to help diagnose it might be
Running with emitDeclarationOnly if printTime is high.
Read up instructions on Reporting Compiler Performance Issues.
showConfig
https://github.com/microsoft/TypeScript/wiki/Performance#controlling-types-inclusion 7/11
2/10/2021 Performance · microsoft/TypeScript Wiki
It's not always obvious what settings a compilation is being run with when running tsc , especially given that tsconfig.json s can extend other
configuration files. showConfig can explain what tsc will calculate for an invocation.
tsc --showConfig
traceResolution
Running with traceResolution can help explain why a file was included in a compilation. The emit is somewhat verbose, so you might want to redirect
output to a file.
If you find a file that shouldn't be present, you may need to look into fixing up your include / exclude lists in your tsconfig.json , or alternatively, you
might need to adjust other settings like types , typeRoots , or paths .
Much of the time, users run into slow performance using 3rd party build tools like Gulp, Rollup, Webpack, etc. Running with tsc --extendedDiagnostics
to find major discrepancies between using TypeScript and the tool can indicate external misconfiguration or inefficiencies.
Is there a major difference in build times between tsc and the build tool with TypeScript integration?
If the build tool provides diagnostics, is there a difference between TypeScript's resolution and the build tool's?
Does the build tool have its own configuration that could be the cause?
Does the build tool have configuration for its TypeScript integration that could be the cause? (e.g. options for ts-loader?)
Upgrading Dependencies
Sometimes TypeScript's type-checking can be impacted by computationally intensive .d.ts files. This is rare, but can happen. Upgrading to a newer
version of TypeScript (which can be more efficient) or to a newer version of an @types package (which may have reverted a regression) can often solve
the issue.
Performance Tracing
In some cases, the approaches above might not give you enough insight to understand why TypeScript feels slow. TypeScript 4.1 and higher provides a
--generateTrace option that can give you a sense of the work the compiler is spending time on. --generateTrace will create an output file that can be
analyzed within Edge or Chrome.
Ideally, TypeScript will be able to compile your project without any errors, though it's not a strict requirement for tracing. Once you're ready to get a
trace, you can run TypeScript with the --generateTrace flag.
You can read more about performance tracing in more detail here.
⚠ Warning: A performance trace may include information from your workspace, including file paths and source code. If you have any concerns about
posting this publicly on GitHub, let us know and you can share the details privately.
https://github.com/microsoft/TypeScript/wiki/Performance#controlling-types-inclusion 8/11
2/10/2021 Performance · microsoft/TypeScript Wiki
⚠ Warning: The format of performance trace files is not stable, and may change from version to version.
Common Issues
Once you've trouble-shooted, you might want to explore some fixes to common issues. If the following solutions don't work, it may be worth filing an
issue.
As mentioned above, the include / exclude options can be misused in several ways.
node_modules was accidentally included from deeper folder exclude was not set "exclude": ["**/node_modules", "**/.*/"]
node_modules was accidentally included from deeper folder "exclude": ["node_modules"] "exclude": ["**/node_modules", "**/.*/"]
Hidden dot files (e.g. .git ) were accidentally included "exclude": ["**/node_modules"] "exclude": ["**/node_modules", "**/.*/"]
Unexpected files are being included. include was not set "include": ["src"]
Filing an Issue
If your project is already properly and optimally configured, you may want to file an issue.
The best reports of performance issues contain easily obtainable and minimal reproductions of the problem. In other words, a codebase that can easily
be cloned over git that contains only a few files. They require either no external integration with build tools - they can either be invoked via tsc or use
isolated code which consumes the TypeScript API. Codebases that require complex invocations and setups cannot be prioritized.
We understand that this is not always easy to achieve - specifically, because it is hard to isolate the source of a problem within a codebase, and because
sharing intellectual property may be an issue. In some cases, the team will be willing to send a non-disclosure agreement (NDA) if we believe the issue is
highly impactful.
Regardless of whether a reproduction is possible, following these directions when filing issues will help us provide you with performance fixes.
Sometimes you'll witness performance issues in both build times as well as editing scenarios. In these cases, it's best to focus on the TypeScript compiler.
First, a nightly version of TypeScript should be used to ensure you're not hitting a resolved issue:
# or
The version of TypeScript that was installed (i.e. npx tsc -v or yarn tsc -v )
The version of Node on which TypeScript ran (i.e. node -v )
The output of running with extendedDiagnostics ( tsc --extendedDiagnostics -p tsconfig.json )
Ideally, a project that demonstrates the issues being encountered.
Output logs from profiling the compiler ( isolate-*-*-*.log and *.cpuprofile files)
It is important to provide the team with diagnostic traces by running Node.js v10+ with the --trace-ic flag alongside TypeScript with the --
generateCpuProfile flag:
Here ./node_modules/typescript/lib/tsc.js can be replaced with any path to where your version of the TypeScript compiler is installed, and
tsconfig.json can be any TypeScript configuration file. profile.cpuprofile is an output file of your choice.
--generateCpuProfile will emit to a file with the name of your choice. In the above example, it will be a file named profile.cpuprofile .
⚠ Warning: These files may include information from your workspace, including file paths and source code. Both of these files are readable as
plain-text, and you can modify them before attaching them as part of a GitHub issue. (e.g. to scrub them of file paths that may expose internal-only
information).
However, if you have any concerns about posting these publicly on GitHub, let us know and you can share the details privately.
Editing performance issues are slightly more involved, but the same ideas apply: clone-able minimal repro codebases are ideal, and though in some
cases the team will be able to sign an NDA to investigate and isolate issues.
Including the output from tsc --extendedDiagnostics is always good context, but taking a TSServer trace is the most helpful.
⚠ Warning: A TSServer log may include information from your workspace, including file paths and source code. If you have any concerns about posting
this publicly on GitHub, let us know and you can share the details privately.
Pages 58
User documentation
News
Roadmap
Breaking Changes
API Breaking Changes
Debugging TypeScript
Performance
https://github.com/microsoft/TypeScript/wiki/Performance#controlling-types-inclusion 10/11
2/10/2021 Performance · microsoft/TypeScript Wiki
Performance-Tracing
Debugging-Language-Service-in-VS-Code
Getting-logs-from-TS-Server-in-VS-Code
JavaScript-Language-Service-in-Visual-Studio
Providing-Visual-Studio-Repro-Steps
Contributing to TypeScript
Contributing to TypeScript
TypeScript Design Goals
Coding Guidelines
Spec conformance testing
Useful Links for TypeScript Issue Management
Writing Good Design Proposals
Compiler Internals
Deployment
Architectural Overview
Using the Compiler API
Using the Language Service API
Standalone Server (tsserver)
Dev Mode in Visual Studio
TypeScript MSBuild In Depth
Debugging Language Service in VS Code
Writing a Language Service Plugin
FAQs
FAQ
FAQs for API Consumers
https://github.com/microsoft/TypeScript.wiki.git
https://github.com/microsoft/TypeScript/wiki/Performance#controlling-types-inclusion 11/11