How to compile Scala code faster with the 'fsc' command-line compiler

This is an excerpt from the Scala Cookbook. This is a short recipe, Recipe 14.9, “How to compile your Scala code faster with the 'fsc' command-line compiler.”

Problem

You’re making changes to a Scala project and recompiling it with scalac, and you’d like to reduce the compile time.

Solution

Use the fsc command instead of scalac to compile your code:

$ fsc *.scala

The fsc command works by starting a compilation daemon and also maintains a cache, so compilation attempts after the first attempt run much faster than scalac.

Discussion

Although the primary advantage is that compile times are significantly improved when recompiling the same code, it’s important to be aware of a few caveats, per the fsc manpage:

  • “The tool is especially effective when repeatedly compiling with the same class paths, because the compilation daemon can reuse a compiler instance.”
  • “The compilation daemon is smart enough to flush its cached compiler when the class path changes. However, if the contents of the class path change, for example due to upgrading a library, then the daemon should be explicitly shut down with -shutdown.”

As an example of the second caveat, if the JAR files on the classpath have changed, you should shut down the daemon, and then reissue your fsc command:

$ fsc -shutdown
[Compile server exited]

$ fsc *.scala

On Unix systems, running fsc creates a background process with the name CompileServer. You can see information about this process with the following ps command:

$ ps auxw | grep CompileServer

See the fsc manpage for more information.

See Also

  • The fsc manpage (type man fsc at the command line).
  • When using SBT, you can achieve similar performance improvements by working in the SBT shell instead of your operating system’s command line. See Recipe 18.2, “Compiling, Running, and Packaging a Scala Project with SBT” for more information.