Make your Scala shell scripts run faster with the "savecompiled" argument

I was just reading the Scala man page, looking for something else, when I ran across this tip on how to speed up the execution of Scala shell scripts, using the savecompiled flag of the scala command:


Save the compiled version of scripts in order to  speed  up  later  executions  of  the  same
script.   When  running a script, save the compiled version of in a file with the same name as
the script but with an extension of .jar.  On subsequent runs of the same script, the 
pre-compiled .jar file will be used if it is newer than the script file.

I just tested this with the simple example that they include at the bottom of the Scala man page:

exec scala -savecompiled "$0" "$@"
Console.println("Hello, world!")
argv.toList foreach Console.println

I saved that script to a file named, then ran the script like this:

$ sh

After running the script, I looked in the current directory with the ls command, and saw that a jar file had indeed been created for me:

drwxr-xr-x  5 Al  Al   170 May 14 09:06 .
drwxr-xr-x  3 Al  Al   102 Apr  4 17:58 ..
-rw-r--r--  1 Al  Al   118 May 14 09:06
-rw-r--r--  1 Al  Al  2727 May 14 09:06

Checking the run times

You can tell that the Scala script runs significantly faster after the jar file has been created, and as a quick little test, I deleted the jar file, then ran the script again, and saw this run time:

# run time without the jar file

$ time sh a b
Hello, world!

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

After this run the jar file was automatically created again, so when I ran the script one more time, I got this output:

# run time with the jar file

$ time sh a b
Hello, world!

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

As you can see from the "real" time output, the run time after the shell script has been compiled to a jar file is much faster, less than half a second, compared to more than 1.5 seconds without the jar file.

As I keep trying to embed Scala in my brain, I've been writing all of my shell scripts with Scala, so this is a pretty cool tip; I hope you like it also.

This website is a little one-man operation. If you found this information helpful, I’d appreciate it if you would share it.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Enter the characters shown in the image.