Is it worth it to precompile your TypeScript Node.js code?

These benchmarks were taken quite a while ago now, and the landscape; and more alternative solutions have emerged since. As of early 2022, I was not happy with any of the main options and as such developed my own, xnr.

Your intuition may have been that your code would be faster by pre-compiling your TypeScript code - but intuition is just intuition.

Even if it was faster - would it be noticeable?

I was determined to find the answer - so I built a couple benchmarks and tried them out on the most common scenarios.

Benchmark 1 - Hello World

Above are the times for a simple “Hello World” program.

// index.ts
console.log("Hello world!);

It is perhaps surprising to see that the ts-node compiles and runs it in the fastest time.

The ts-node script compiles during its run and so an accurate measure of the time allocated to the compilation step and running the results is difficult to gauge.

Still, it finishes its run before the other fastest compiler can complete it’s compilation step; as such, it must also have the fastest compiler.

Benchmark 2 - Express server

This benchmark is for time to start up an express http server, which validates sudoku solutions (returning true or false) and serves a simple UI to enter a solution to check.

Notably, the code imports a large number of dependencies (express uses a bunch), and uses 2 source typescript files instead of 1, and some newer JS features like for-of loops were also included.

Again, ts-node is fastest from start to finish, and its lead (as a percentage) has increased.

The bundlers rollup and webpack both were slower than tsc; this is likely due to bringing their dependencies inline, and compressing the results (tsc does not bundle or compress output JS).

This example also allows us to see the performance benefit of bundling code into a single file and compressing it.

tsc took 14% longer than webpack, and 9% longer than rollup.

Conclusion

For scripting in TypeScript, ts-node is the clear choice. Note that ts-node does not typecheck, which is why it is faster.

For production environments, webpack is probably the best choice; it had the best perfomance, and it’s main negative (large bundles) aren’t really felt on the server-side.

If you’re running on a low memory system in production, using tsc would be best, as it doesn’t need to read the whole bundle into memory to run.