14.13. Make Your Scala Scripts Run Faster

Problem

You love using Scala as a scripting language, but you’d like to eliminate the lag time in starting up a script.

Solution

Use the -savecompiled argument of the Scala interpreter to save a compiled version of your script.

A basic Scala script like this:

#!/bin/sh
exec scala "$0" "$@"
!#

println("Hello, world!")
args foreach println

consistently runs with times like this on one of my computers:

real   0m1.573s
user   0m0.574s
sys     0m0.089s

To improve this, add the -savecompiled argument to the Scala interpreter line:

#!/bin/sh
exec scala -savecompiled "$0" "$@"
!#

println("Hello, world!")
args foreach println

Then run the script once. This generates a compiled version of the script. After that, the script runs with a consistently lower real time (wall clock) on all subsequent runs:

real   0m0.458s
user   0m0.487s
sys    0m0.075s

Precompiling your script shaves a nice chunk of time off the runtime of your script, even for a simple example like this.

Discussion

When you run your script the first time, Scala generates a JAR file that matches the name of your script. For instance, I named my script test1.sh, and then ran it like this:

$ ./test1.sh

After running the script, I looked at the directory contents and saw that Scala created a file named test1.sh.jar. Scala creates this new file and also leaves your original script in place.

On subsequent runs, Scala sees that there’s a JAR file associated with the script, and if the script hasn’t been modified since the JAR ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.