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:

-savecompiled

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:

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

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

$ sh foo.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 foo.sh
-rw-r--r--  1 Al  Al  2727 May 14 09:06 foo.sh.jar

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 foo.sh a b
Hello, world!
a
b

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 foo.sh a b
Hello, world!
a
b

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.

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.
By submitting this form, you accept the Mollom privacy policy.